Common string filtering methods in Asp.net

Source: Internet
Author: User

Using system;
Using system. text;
Using system. Text. regularexpressions;

Namespace bjmti
{
/// <Summary>
/// Summary of include.
/// </Summary>
Public class include
{
Public include ()
{
//
// Todo: add the constructor logic here
//
}

# Region string truncation Function
/// <Summary>
/// String truncation Function
/// </Summary>
/// <Param name = "inputstring"> string to be truncated </param>
/// <Param name = "len"> length to be intercepted </param>
/// <Returns> string </returns>
///
Public static string cutstring (string inputstring, int Len)
{


Asciiencoding ASCII = new asciiencoding ();
Int templen = 0;
String tempstring = "";
Byte [] S = ASCII. getbytes (inputstring );
For (INT I = 0; I <S. length; I ++)
{
If (INT) s [I] = 63)
{
Templen + = 2;
}
Else
{
Templen + = 1;
}

Try
{
Tempstring + = inputstring. substring (I, 1 );
}
Catch
{
Break;
}

If (templen> Len)
Break;
}
//// If yes, add half ellipsis
// Byte [] mybyte = system. Text. encoding. Default. getbytes (inputstring );
// If (mybyte. length> Len)
// Tempstring + = "... ";

Return tempstring;
}
# Endregion

# Region generate a unique file name composed of dates
/// <Summary>
/// Generate a unique file name consisting of dates
/// </Summary>
/// <Returns> string </returns>
///
Public static string makefilename ()
{
String newfilename;
String datename = system. datetime. Now. tostring ("yyyymmddhhmmss ");
System. Random SRD = new random ();
Int srdname = SRD. Next (1000 );
Newfilename = datename + srdname. tostring ();
Return newfilename;
}
# Endregion

# Region filter special characters
/// <Summary>
/// Filter special characters
/// </Summary>
/// <Param name = "inputstr"> string </param>
/// <Returns> string </returns>
Public static string cutbadstr (string inputstr)
{
Inputstr = inputstr. tolower (). Replace (",","");
Inputstr = inputstr. tolower (). Replace ("<", "& lt ;");
Inputstr = inputstr. tolower (). Replace (">", "& gt ;");
Inputstr = inputstr. tolower (). Replace ("% ","");
Inputstr = inputstr. tolower (). Replace (".","");
Inputstr = inputstr. tolower (). Replace (":","");
Inputstr = inputstr. tolower (). Replace ("#","");
Inputstr = inputstr. tolower (). Replace ("&","");
Inputstr = inputstr. tolower (). Replace ("$ ","");
Inputstr = inputstr. tolower (). Replace ("^ ","");
Inputstr = inputstr. tolower (). Replace ("*","");
Inputstr = inputstr. tolower (). Replace ("'","");
Inputstr = inputstr. tolower (). Replace ("","");
Inputstr = inputstr. tolower (). Replace ("~ ","");
Inputstr = inputstr. tolower (). Replace ("or ","");
Inputstr = inputstr. tolower (). Replace ("and ","");
Return inputstr;

}
# Endregion

# Region filter HTML tags
/// <Summary>
/// Filter HTML tags
/// </Summary>
/// <Param name = "htmlstr"> string to be filtered </param>
/// <Returns> string </returns>
///

Public static string cuthtml (string strhtml)
{
String [] aryreg = {
@ "<SCRIPT [^>] *?>. *? </SCRIPT> ",

@ "<(\/\ S *)?!? (\ W + :)? \ W +) (\ W + (\ s * =? \ S * (["" ']) (bytes) *? \ 7 | \ W +) |. {0}) | \ s )*? (\/\ S *)?> ",
@ "([\ R \ n]) [\ s] + ",
@ "& (Quot | #34 );",
@ "& (Amp | #38 );",
@ "& (LT | #60 );",
@ "& (GT | #62 );",
@ "& (Nbsp | #160 );",
@ "& (Iexcl | #161 );",
@ "& (Cent | #162 );",
@ "& (Pound | #163 );",
@ "& (Copy | #169 );",
@ "& # (\ D + );",
@ "--> ",
@ "<! --. * \ N"
};

String [] aryrep = {
"",
"",
"",
"\"",
"&",
"<",
"> ",
"",
"\ XA1", // CHR (161 ),
"\ Xa2", // CHR (162 ),
"\ Xa3", // CHR (163 ),
"\ Xa9", // CHR (169 ),
"",
"\ R \ n ",
""
};

String newreg = aryreg [0];
String stroutput = strhtml;
For (INT I = 0; I <aryreg. length; I ++)
{
RegEx = new RegEx (aryreg [I], regexoptions. ignorecase );
Stroutput = RegEx. Replace (stroutput, aryrep [I]);
}
Stroutput. Replace ("<","");
Stroutput. Replace ("> ","");
Stroutput. Replace ("\ r \ n ","");
Return stroutput;
}
# Endregion

# Fixed region title Length


/// <Summary>
/// <Table Style = "font-size: 12px">
/// <Tr> <TD> <B> function description </B>: Fill in or cut off the original string to the specified length </TD> </tr>
/// <Tr> <TD> <B> creator </B>: </TD> </tr>
/// <Tr> <TD> <B> creation time </B>: </TD> </tr>
/// </Table>
/// </Summary>
/// <Param name = "stroriginal"> original string </param>
/// <Param name = "maxtruelength"> String Length in bytes </param>
/// <Param name = "chrpad"> Fill character </param>
/// <Param name = "blncuttail"> when the byte length of a string exceeds maxtruelength, extra characters are truncated. </param>
/// <Returns> string after filling or truncation </returns>
Static Public String padrighttruelen (string stroriginal, int maxtruelength, char chrpad, bool blncuttail)
{
String strnew = stroriginal;

If (stroriginal = NULL | maxtruelength <= 0)
{
Strnew = "";
Return strnew;
}

Int truelen = truelength (stroriginal );
If (truelen> maxtruelength) // exceeds maxtruelength
{
If (blncuttail) // Truncation
{
For (INT I = stroriginal. Length-1; I> 0; I --)
{
Strnew = strnew. substring (0, I );
If (truelength (strnew) = maxtruelength)
Break;
Else if (truelength (strnew) <maxtruelength)
{
Strnew + = chrpad. tostring ();
Break;
}
}
}
}
Else // fill
{
For (INT I = 0; I <maxtruelength-truelen; I ++)
{
Strnew + = chrpad. tostring ();
}
}

Return strnew;
}

// Main method
Public static string cutstringtitle (string inputstring, int I)
{
Return padrighttruelen (inputstring, I, '', true );
}

/// <Summary>
/// <Table Style = "font-size: 12px">
/// <Tr> <TD> <B> function description </B>: the length of the string in bytes </TD> </tr>
/// <Tr> <TD> <B> creator </B>: </TD> </tr>
/// <Tr> <TD> <B> creation time </B>: </TD> </tr>
/// </Table>
/// </Summary>
/// <Param name = "str"> string </param>
/// <Returns> String Length in bytes </returns>
Static public int truelength (string Str)
{
Int lentotal = 0;
Int n = Str. length;
String strword = "";
Int ASC;
For (INT I = 0; I <n; I ++)
{
Strword = Str. substring (I, 1 );
ASC = convert. tochar (strword );
If (ASC <0 || ASC> 127)
Lentotal = lentotal + 2;
Else
Lentotal = lentotal + 1;
}

Return lentotal;
}
# Endregion

# Region close current window (static)
/// <Summary>
/// (Descript) Close the current window (static)
/// (Author) warfu
/// (Date) 2007-08-28
/// </Summary>
Public static void closewindow ()
{
System. Web. httpcontext. Current. response. Write ("<script language = JavaScript> window. Close () </SCRIPT> ");
}
# Endregion

# Region open a new window without a toolbar (static)

/// <Summary>
/// Return the JS script -- window. Open ('','')
/// </Summary>
/// <Param name = "url"> URL </param>
/// <Param name = "name"> Target </param>
/// <Returns> </returns>
Public static string openweb (string URL, string name)
{
// Output prompt information
Return "<script language = JavaScript> window. Open ('" + URL + "', '" + name + "') </SCRIPT> ";
}

/// <Summary>
/// Open a new window without a toolbar (static)
/// </Summary>
/// <Param name = "str_url"> page path </param>
/// <Param name = "int_height"> window height </param>
/// <Param name = "int_width"> window width </param>
/// <Param name = "str_webname"> window name </param>
Public static void OpenWindow (string str_url, int int_height, int int_width, string str_webname)
{
// Construct Javascript
String str_javascript = @ "<script language = 'javascript '>
Window. open ('"mailto: + str_url + @ % 22',' % 22 + str_webname + @ % 22', 'height =" + int_height mailto: + @ % 22 ', 'width = "+ int_width mailto: + @ % 22', 'top = 0, Left = 0, location = No, menubar = No, resizable = Yes, scrollbars = Yes, status = Yes, titlebar = Yes, toolbar = No, directories = no ');
</SCRIPT> ";

System. Web. httpcontext. Current. response. Write (str_javascript );


}
# Endregion

}
}
 

We know that Unicode is used internally in C # (. NET) to store strings, so that sometimes some unpleasant things happen when processing strings. For example, if a string contains Chinese characters and we want to obtain a fixed-length string, it is quite troublesome. The following provides a solution. In this solution, we have implemented the following functions:

Obtain the left-side substring of the given string. The size of the substring is the specified length;
If the given string length is greater than the given length, add "..." to the end of the substring.
Avoid the occurrence of half Chinese characters.
The source code is as follows:

Private string getleftsubstring (string content, int length)
{
Encoding encoding = encoding. getencoding ("gb2312 ");
Stringbuilder sb = new stringbuilder ();
Int totallength = 0;
Foreach (char contentchar in content)
{
Int size = encoding. getbytecount (New char [] {contentchar });
If (totallength + size> length-2)
{
SB. append ("..");
Break;
}
SB. append (contentchar );
Totallength + = size;
}
Return sb. tostring ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.