string-handling classes commonly used in asp.net

Source: Internet
Author: User
Tags foreach chr httpcontext lowercase md5 trim
The code is as follows Copy Code

Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Text;

Namespace EC
{
///
Common function base class
///
public class Funobject
{
#region Replacement string
///
Features: Replacing characters
///
String
Replace the ' string
public static string Filtersql (String strvalue)
{
String str = "";
str = strvalue.replace ("" "," ");
return str;
}
#endregion

#region Convert HTML operations on the contents of a table Form.
///
Function: Transforms HTML operations on the contents of a table Form,
///
HTML string
///
public static string Htmlcode (String fstring)
{
String str = "";
str = fstring.replace (">", ">");
str = fstring.replace ("<", "<");
str = Fstring.replace ("", "");
str = Fstring.replace ("n", "
");
str = fstring.replace ("R", "
");
str = fstring.replace ("rn", "
");

return str;
}
#endregion

#region Judge whether: return value: √orx
///
Judge whether: Return value: √orx
///
True or False
√orx
public static string judgement (bool B)
{
string s = "";
if (b = = true)
s = "√";
Else
s = "X";
return s;
}
#endregion

#region Intercept string
///
///feature: Intercept string length
///
///the string to intercept
///string length
///true: Add ..., flase: no
// /
public static string GetString (string str, int length, bool flg)
{
int i = 0, j = 0;
foreach (char chr in str)
{
if ((int) CHR > 127)
{
i = 2;
}
Else
{
i++;
}
if (i > Length)
{
str = str. Substring (0, J);
if (FLG)
str + = "...";
break;
}
J + +;
}
return str;
}
#endregion

#region Intercept string + ...
///
Intercept string + ...
///
///
///
///
public static string Cutstring (string strinput, int intlen)/intercept string
{
ASCIIEncoding ASCII = new ASCIIEncoding ();
int intlength = 0;
String strstring = "";
Byte[] s = ASCII. GetBytes (strinput);
for (int i = 0; i < s.length; i++)
{
if ((int) s[i] = = 63)
{
Intlength + 2;
}
Else
{
Intlength + 1;
}

Try
{
Strstring + + strinput.substring (i, 1);
}
Catch
{
Break
}

if (Intlength > Intlen)
{
Break
}
}
If it's truncated, add half an ellipsis.
byte[] MyByte = System.Text.Encoding.Default.GetBytes (strinput);
if (MyByte. Length > Intlen)
{
strstring + = "...";
}
return strstring;
}
#endregion

#region String Division function
///
///String Division
///
///
///
///
///
public string stringsplit (str ing strings, int index, string separ)
{
String[] s = strings. Split (char. Parse (Separ));
return S[index];
}
#endregion

#region exploded string as an array
///
///string function
///
///The string to be decomposed
///delimiter, which can be a string type
///character list
Public Static string[] Splitstr (String str, string splitstr)
{
if (splitstr!= "")
{
System.Collections.Array List C = new System.Collections.ArrayList ();
while (true)
{
int thissplitindex = str. IndexOf (SPLITSTR);
if (thissplitindex >= 0)
{
C.add (str. Substring (0, Thissplitindex));
str = str. Substring (Thissplitindex + splitstr). Length);
}
Else
{
C.add (str);
break;
}
}
string[] D = new String[c.count];
for (int i = 0; i < C.count i++)
{
D[i] = c[i]. ToString ();
}
return D;
}
Else
{
return new string[] {str};
}
}
#endregion

#region URL Encoding
///
URL encoding
///
String
///
public static string urlencoding (String str)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes (str);
Return System.Text.Encoding.UTF8.GetString (bytes). ToString ();
}
#endregion

#region Get the Configuration field value in Web.config
///
Get Global configuration parameters
///
Key Name
Parameters
public static string Getapp (String key)
{
System.Configuration.AppSettingsReader appr = new System.Configuration.AppSettingsReader ();
Try
{
String str = (string) appr. GetValue (Key, typeof (String));
if (str = NULL | | | str = = "") return null;
return str;
}
catch (Exception E) {}
return null;
}

#endregion

#region returns a bit based on whether the passed-in string is yes/no
///
Returns a bit based on whether the passed-in string is yes/no
///
///
///
public static int Getbitbool (string flg)
{
int str = 0;
Switch (FLG. ToLower ())
{
Case "Yes":
str = 1;
Break
Case "No":
str = 0;
Break
Default
Break
}
return str;
}
#endregion

#region HTML Encoding
///
HTML encoding
///
///
///
public static string HtmlEncode (String strinput)
{
String str;
Try
{
str = HttpContext.Current.Server.HtmlEncode (strinput);
}
Catch
{
str = "Error";
}
return str;
}
///
HTML decoding
///
///
///
public static string HtmlDecode (String strinput)
{
String str;
Try
{
str = HttpContext.Current.Server.HtmlDecode (strinput);
}
Catch
{
str = "Error";
}
return str;
}
#endregion

#region detects whether a character character, exists in another character, exists, returns True, or returns false
///
Detects a character character, whether it exists in another character, exists, returns True, or returns false
///
Raw string
Target string
///
public static bool Isenglish (string srcstring, String aimstring)
{
bool Rev. = true;
String Chr;
if (aimstring = = "" | | Aimstring = = null) return false;
for (int i = 0; i < aimstring.length; i++)
{
CHR = aimstring.substring (i, 1);
if (Srcstring.indexof (CHR) < 0)
{
return false;
Break
}

}
return Rev;
}
#endregion

#region detect if the string contains Chinese and Chinese length
///
Detect if the string contains Chinese and Chinese length
///
The string to detect
Chinese string length
public static int cnstringlength (String str)
{
ASCIIEncoding n = new ASCIIEncoding ();
Byte[] B = n.getbytes (str);
int l = 0; L is the actual length of the string
for (int i = 0; I <= b.length-1; i++)
{
if (b[i] = = 63)//Judge whether it is Chinese character or full foot symbol
{
l++;
}
}
return l;

}
#endregion

#region take a few characters to the right of the string
///
Take a few characters to the right of the string
///
String
Several characters to the right
///
public static string Getstrright (string str, int length)
{
String Rev = "";

if (str. Length < length)
{
Rev = str;

}
Else
{
Rev = str. Substring (str. Length-length, length);
}
return Rev;


}
#endregion

#region Replace the string on the right

///
Replace the string on the right
///
String
String to the right
The string to be replaced with
///
public static string Repstrright (String str, string strsrc, String straim)
{

String Rev = "";
if (Getstrright str, strsrc. Length)!= strsrc)
{
Rev = str;
}
Else
{
Rev = str. Substring (0, str. Length-strsrc. Length). ToString () + Straim. ToString ();
}
return Rev;
}
#endregion
}

}

Example Two

Code for some common string operations! We look at the code directly!!

The code is as follows Copy Code

Using System;

Namespace Web.stringutil
{
<summary>
String Manipulation Tool Set
</summary>
public class Stringutil
{
Public Stringutil ()
{
//
TODO: Add constructor logic here
//
}

&lt;summary&gt;


Deletes the specified string from the tail in the string


&lt;/summary&gt;


&lt;param name= "Sourcestring" &gt;&lt;/param&gt;


&lt;param name= "Removedstring" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Remove (String sourcestring,string removedstring)


{


Try


{


if (Sourcestring.indexof (removedstring) &lt; 0)


{


throw new Exception ("The original string does not contain a removal string!") ");


}


string result = sourcestring;


int lengthofsourcestring = Sourcestring.length;


int lengthofremovedstring = Removedstring.length;


int startIndex = lengthofsourcestring-lengthofremovedstring;


String tempsubstring = Sourcestring.substring (StartIndex);


if (tempsubstring.toupper () = = Removedstring.toupper ())


{


result = Sourcestring.remove (startindex,lengthofremovedstring);


}


return result;


}


Catch


{


return sourcestring;


}


}

&lt;summary&gt;


Get the string to the right of the split break


&lt;/summary&gt;


&lt;param name= "Sourcestring" &gt;&lt;/param&gt;


&lt;param name= "Splitchar" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Rightsplit (String sourcestring, char Splitchar)


{


String Result=null;


string[] tempstring = Sourcestring.split (Splitchar);


if (Tempstring.length &gt;0)


{


result = Tempstring[tempstring.length-1]. ToString ();


}


return result;


}





&lt;summary&gt;


Get the string to the left of the split break


&lt;/summary&gt;


&lt;param name= "Sourcestring" &gt;&lt;/param&gt;


&lt;param name= "Splitchar" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Leftsplit (String sourcestring, char Splitchar)


{


String Result=null;


string[] tempstring = Sourcestring.split (Splitchar);


if (Tempstring.length &gt;0)


{


result = Tempstring[0]. ToString ();


}


return result;


}

&lt;summary&gt;


Remove the last comma


&lt;/summary&gt;


&lt;param Name= "origin" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Dellastcomma (String origin)


{


if (Origin. IndexOf (",") = =-1)


{


return origin;


}


return origin. Substring (0,origin. LastIndexOf (","));


}

&lt;summary&gt;


Remove Invisible characters


&lt;/summary&gt;


&lt;param name= "Sourcestring" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Deleteunvisiblechar (String sourcestring)


{


System.Text.StringBuilder Sbuilder = new System.Text.StringBuilder (131);


for (int i = 0;i &lt; sourcestring.length; i++)


{


int Unicode = Sourcestring[i];


if (Unicode &gt;= 16)


{


Sbuilder.append (Sourcestring[i]. ToString ());


}


}


return sbuilder.tostring ();


}

&lt;summary&gt;


Gets the merged string for an array element


&lt;/summary&gt;


&lt;param name= "Stringarray" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string getarraystring (string[] stringarray)


{


string totalstring = null;


for (int i=0;i&lt;stringarray.length;i++)


{


totalstring = totalstring + stringarray[i];


}


return totalstring;


}

&lt;summary&gt;


Gets the number of times a string appears in a string array


&lt;/summary&gt;


&lt;param name= "Stringarray" type= "string[]" &gt;


&lt;para&gt;


///


&lt;/para&gt;


&lt;/param&gt;


&lt;param name= "findstring" type= "string" &gt;


&lt;para&gt;


///


&lt;/para&gt;


&lt;/param&gt;


&lt;returns&gt;


A int Value


&lt;/returns&gt;


public static int Getstringcount (string[] stringarray,string findstring)


{


int count =-1;


String totalstring = Getarraystring (Stringarray);


string subString = totalstring;

while (Substring.indexof (findstring) >=0)
{
subString = totalstring.substring (Substring.indexof (findstring));
Count + 1;
}
return count;
}

&lt;summary&gt;


Gets the number of times a string appears in a string


&lt;/summary&gt;


&lt;param name= "Stringarray" type= "string" &gt;


&lt;para&gt;


Original string


&lt;/para&gt;


&lt;/param&gt;


&lt;param name= "findstring" type= "string" &gt;


&lt;para&gt;


Match string


&lt;/para&gt;


&lt;/param&gt;


&lt;returns&gt;


Number of matching strings


&lt;/returns&gt;


public static int Getstringcount (string sourcestring,string findstring)


{


int count = 0;


int findstringlength = Findstring.length;


string subString = sourcestring;

while (Substring.indexof (findstring) >=0)
{
subString = substring.substring (Substring.indexof (findstring) +findstringlength);
Count + 1;
}
return count;
}

&lt;summary&gt;


Intercepts all characters starting from startstring to the end of the original string


&lt;/summary&gt;


&lt;param name= "sourcestring" type= "string" &gt;


&lt;para&gt;


///


&lt;/para&gt;


&lt;/param&gt;


&lt;param name= "startstring" type= "string" &gt;


&lt;para&gt;


///


&lt;/para&gt;


&lt;/param&gt;


&lt;returns&gt;


A String Value


&lt;/returns&gt;


public static string Getsubstring (String sourcestring,string startstring)


{


Try


{


int index = Sourcestring.toupper (). IndexOf (startstring);


if (index&gt;0)


{


Return sourcestring.substring (index);


}


return sourcestring;


}


Catch


{


Return "";


}


}

        public static string getsubstring (String sourcestring,string Beginremovedstring,string endremovedstring)
        {
             Try
             {
                 if (Sourcestring.indexof (beginremovedstring)!=0)
                 {   
                     beginremovedstring = "";
               }

if (Sourcestring.lastindexof (endremovedstring,sourcestring.length-endremovedstring.length) &lt;0)


{


endremovedstring = "";


}


int startIndex = Beginremovedstring.length;


int length = Sourcestring.length-beginremovedstring.length-endremovedstring.length;


if (length&gt;0)


{


Return sourcestring.substring (startindex,length);


}


return sourcestring;


}


Catch


{


return sourcestring;;


}


}





&lt;summary&gt;


To remove the length of a string by number of bytes


&lt;/summary&gt;


&lt;param name= "Strtmp" &gt; string to be evaluated &lt;/param&gt;


&lt;returns&gt; number of bytes in the string &lt;/returns&gt;


public static int GetByteCount (string strtmp)


{


int intcharcount=0;


for (int i=0;i&lt;strtmp.length;i++)


{


if (System.Text.UTF8Encoding.UTF8.GetByteCount (strtmp.substring (i,1)) ==3)


{


intcharcount=intcharcount+2;


}


Else


{


intcharcount=intcharcount+1;


}


}


return intcharcount;


}

&lt;summary&gt;


By number of bytes at the position of the string


&lt;/summary&gt;


&lt;param name= "Intins" &gt; string position &lt;/param&gt;


&lt;param name= "Strtmp" &gt; string to be evaluated &lt;/param&gt;


&lt;returns&gt; byte position &lt;/returns&gt;


public static int Getbyteindex (int intins,string strtmp)


{


int intreins=0;


if (Strtmp.trim () = "")


{


return intins;


}


for (int i=0;i&lt;strtmp.length;i++)


{


if (System.Text.UTF8Encoding.UTF8.GetByteCount (strtmp.substring (i,1)) ==3)


{


intreins=intreins+2;


}


Else


{


intreins=intreins+1;


}


if (intreins&gt;=intins)


{


intreins=i+1;


Break


}


}


return intreins;


}


}


}

Example Three

The code is as follows Copy Code

Using System;
Using System.Collections;
Using System.Collections.Generic;
Using System.Text;
Using System.Text.RegularExpressions;
Using System.Security.Cryptography;
Using System.IO;
Using System.Text;

Namespace Stringclass


{


public class Stringhelper


{


&lt;summary&gt;


Remove all spaces in a string


&lt;/summary&gt;


&lt;param name= "_str" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Removeblank (String _str)


{


String strtemp = "";


Charenumerator CEnumerator = _str. GetEnumerator ();


while (Cenumerator.movenext ())


{


byte[] array = new BYTE[1];


Array = System.Text.Encoding.ASCII.GetBytes (CEnumerator.Current.ToString ());


int asciicode = (short) (array[0]);


if (Asciicode!= 32)


{


strtemp + + CEnumerator.Current.ToString ();


}


}


return strtemp;


}




&lt;summary&gt;


Intercepts the string and restricts the string length more than the given length + ...


&lt;/summary&gt;


&lt;param name= "str" &gt; the string to be intercepted &lt;/param&gt;


&lt;param name= "Len" &gt; length of each line, more than this length of line wrap &lt;/param&gt;


&lt;param name= "Max" &gt; Output string Maximum length &lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Cutstr (string str, int len, int max)


{


string s = "";


string sheng = "";


if (str. Length &gt; Max)


{


str = str. Substring (0, Max);


Sheng = "";


}


for (int i = 0; i &lt; str. Length; i++)


{


int r = i% Len;


int last = (str. Length/len) * LEN;


if (i!= 0 &amp;&amp; i &lt;= last)


{


if (r = = 0)


{


s + + str. Substring (I-len, Len) + "&lt;br&gt;";


}

}
else if (i > Last)
{
s + + str. Substring (i-1);
Break
}

}
return S + Sheng;
}

&lt;summary&gt;


Intercepts a string, without limiting the length of the string


&lt;/summary&gt;


&lt;param name= "str" &gt; the string to be intercepted &lt;/param&gt;


&lt;param name= "Len" &gt; length of each line, more than this length of line wrap &lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Cutstr (string str, int len)


{


string s = "";


for (int i = 0; i &lt; str. Length; i++)


{


int r = i% Len;


int last = (str. Length/len) * LEN;


if (i!= 0 &amp;&amp; i &lt;= last)


{


if (r = = 0)


{


s + + str. Substring (I-len, Len) + "&lt;br&gt;";


}


}


else if (i &gt; Last)


{


s + + str. Substring (i-1);


Break


}


}


return s;


}

public static string partsubstring (string str, int len)
{
if (str. Length > Len)
{
Return str. Substring (0, Len) + "...";
}
return str;
}

&lt;summary&gt;


This method ensures that the user's input is not malicious


&lt;/summary&gt;


&lt;param name= "Text" &gt; Input string &lt;/param&gt;


&lt;param name= "MaxLength" &gt; Max length &lt;/param&gt;


&lt;returns&gt; the converted string &lt;/returns&gt;


public static string Inputtext (string text, int maxLength)


{


Text = text. Trim ();


if (string. IsNullOrEmpty (text)


return string. Empty;


if (text. Length &gt; MaxLength)


Text = text. Substring (0, maxLength);


Text = Regex.Replace (text, "[\s]{2,}", ""); Two or more spaces


Text = Regex.Replace (text, "&lt;[b| b][r| r]/*&gt;) +| (&lt;[p| P] (. | \ n) "," *?&gt; "); &lt;br&gt;


Text = Regex.Replace (text, "\s*&amp;[n| n][b| b][s| s][p| p];\s*) + "," "); &amp;nbsp;


Text = Regex.Replace (text, &lt;. | \ n) *?&gt; ", String. Empty); Any other tags


Text = text. Replace ("'", "" ");


return text;


}

&lt;summary&gt;


Uppercase characters in string to lowercase


&lt;/summary&gt;


&lt;param name= "str" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Stringtolower (String str)


{


char[] A = str. ToCharArray ();


String strtemp = "";


for (int i = 0; i &lt; a.length; i++)


{


if (Convert.ToInt32 (a[i)) &gt;= &amp;&amp; Convert.ToInt32 (a[i)) &lt;= 90)


strtemp + = A[i]. ToString (). ToLower ();


Else


strtemp + = A[i]. ToString ();


}


return strtemp;


}

&lt;summary&gt;


Encryption


&lt;/summary&gt;


&lt;param name= "str" &gt;&lt;/param&gt;


&lt;param name= "Key" &gt; must be a 8-bit string &lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Encode (string str, int keyIndex)


{


ArrayList Alkey = new ArrayList ();


Alkey.add ("bookt@#+! NumBq2 ");


Alkey.add ("magazine@" (21&AMP;*ID5);


Alkey.add ("thesisdshi}._y");


String key = Alkey[keyindex]. ToString ();


DESCryptoServiceProvider Provider = new DESCryptoServiceProvider ();


Provider. Key = Encoding.ASCII.GetBytes (key. Substring (0, 8));


PROVIDER.IV = Encoding.ASCII.GetBytes (key. Substring (0, 8));


byte[] bytes = encoding.getencoding ("GB2312"). GetBytes (str);


MemoryStream stream = new MemoryStream ();


CryptoStream stream2 = new CryptoStream (stream, provider. CreateEncryptor (), cryptostreammode.write);


Stream2. Write (bytes, 0, bytes. Length);


Stream2. FlushFinalBlock ();


StringBuilder builder = new StringBuilder ();


foreach (Byte num in stream. ToArray ())


{


Builder. AppendFormat ("{0:x2}", num);


}


Stream. Close ();


Return builder. ToString ();


}

&lt;summary&gt;


Des decryption GB2312


&lt;/summary&gt;


&lt;param name= "str" &gt;desc string&lt;/param&gt;


&lt;param name= "Key" &gt;key, must be 8-bit &lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Decode (string str, int keyIndex)


{


ArrayList Alkey = new ArrayList ();


Alkey.add ("bookt@#+! NumBq2 ");


Alkey.add ("magazine@" (21&AMP;*ID5);


Alkey.add ("thesisdshi}._y");


String key = Alkey[keyindex]. ToString ();


DESCryptoServiceProvider Provider = new DESCryptoServiceProvider ();


Provider. Key = Encoding.ASCII.GetBytes (key. Substring (0, 8));


PROVIDER.IV = Encoding.ASCII.GetBytes (key. Substring (0, 8));


byte[] buffer = new BYTE[STR. LENGTH/2];


for (int i = 0; i &lt; (str. LENGTH/2); i++)


{


int num2 = Convert.ToInt32 (str. Substring (i * 2, 2), 0x10);


Buffer[i] = (byte) num2;


}


MemoryStream stream = new MemoryStream ();


CryptoStream stream2 = new CryptoStream (stream, provider. CreateDecryptor (), cryptostreammode.write);


Stream2. Write (buffer, 0, buffer.) Length);


Stream2. FlushFinalBlock ();


Stream. Close ();


Return encoding.getencoding ("GB2312"). GetString (stream. ToArray ());


}

&lt;summary&gt;


MD5 32-bit irreversible encryption


&lt;/summary&gt;


&lt;param name= "S" &gt;&lt;/param&gt;


&lt;param name= "_input_charset" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Getmd5_32 (String str1)


{


string CL1 = str1;


string pwd = "";


MD5 MD5 = MD5. Create ();


After encryption is an array of byte types


Byte[] s = Md5.computehash (Encoding.Unicode.GetBytes (CL1));


Converts an array of byte types to a string by using a loop, which is a regular character formatting gain


for (int i = 0; i &lt; s.length; i++)


{


Use hexadecimal type format for the resulting string. The formatted character is a lowercase letter, and if uppercase (X) is used, the character in the format is upper case.


PWD = pwd + s[i]. ToString ("X");


}


return pwd;


}


&lt;summary&gt;


MD5 16-bit irreversible encryption


&lt;/summary&gt;


&lt;param name= "Convertstring" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static string Getmd5_16 (String convertstring)


{

MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider ();

String t2 = bitconverter.tostring (Md5.computehash (UTF8Encoding.Default.GetBytes (convertstring)), 4, 8);

t2 = T2. Replace ("-", "");

return T2;

}
}
}

Related Article

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.