C # String manipulation functions and methods in asp.net

Source: Internet
Author: User
Tags lowercase readline trim

The

(1) takes the string length <string>. Length;
(2) string to bit code GetBytes (<string>)
(3) string addition recommend StringBuilder SB = new StringBuilder (); sb. Append (<string>); The
(4) truncates part of a string's variables. SubString (starting position, number of bits intercepted); The
(5) checks whether the specified location is a null character char. Iswhitespace (string variable, number of digits),
(6) Check whether the character is a punctuation char. Ispunctuation (' character ');
(7) Converts a character to a number, a code point (int) ' Variable '
(8) Converts a number to a character, and the character (char) code that is represented by the code
(9) Clears the space variable that is included before and after the string. Trim ()
(10) Replace string: String variable. Replace (Original string, new String)
(11) 3 Ways to delete the last character of a string

The code is as follows Copy Code
eg:string s = "1,2,3,4,5,";
A) s.substring (0,s.length-1)//delete last comma
b) s.tostring (). RTrim (', '); Delete comma, follow variable is any valid string
c) s.trimend (', ')//delete comma, followed by variable is an array
Char[] mychar={' 5 ', ', '};//delete ' 5 ' and ', '
S.trimend (MyChar);

(3) Methods of Split
A) separating <string> with a single character;. Split (New char[]{' character '})//<string>. Split (' character ');
b) separating <string> with multiple characters;. Split (New char[2]{' character ', '} ')
c) separating Regex.Split (<string>, "strings", regexoptions.ignorecase) with strings;

(13) format of several output strings

The code is as follows Copy Code
ToString ("n"); Generate 12,345.00
ToString ("C"); Generate ¥12,345.00
ToString ("E"); Generate 1.234500e+004
ToString ("F4"); Generate 12345.0000
ToString ("X"); Generate 3039 (16 binary)
ToString ("P"); Generate 1,234,500.00%

(14) 3 ways to convert 123456789 to 12-345-6789

The code is as follows Copy Code
(a) A = Int. Parse (a). ToString ("##-###-####");
(b) A = A.insert (5, "-"). Insert (2, "-");
(c) Using System.Text.RegularExpressions; First reference
Regex reg = new Regex (@ "^ (d{2}) (D{3}) (D{4}) $");
A = Reg. Replace (A, "$1-$2-$3");

(15) A simple method for outputting 21 a striing str = new string (' A ', 21);
(16) The method of obtaining random numbers

The code is as follows Copy Code
Ramdom r = new Ramdom ();
Int n1 = R.next (); returns nonnegative random integers
Int N2 = R.next (10); Returns a nonnegative random integer less than the specified maximum value (10)
Int n3 = R.next ()%10; Returns a nonnegative random integer less than the specified maximum value (10)
Int N4 = R.next (1,20); Returns a random integer within a specified range (1~20)
Int N5 = r.nextdouble (); To get a random integer between 0.0~1.0

(a) Int32.TryParse (), Int32. Parse (), Convert.ToInt32 () comparison:
is to convert the string to an integer number

The code is as follows Copy Code
Int32.TryParse (string,out int);
Int = Int32. Parse (string);
Int = Convert.ToInt32 (string);

Comparison: Convert.ToInt32 () does not throw an exception at null but returns 0; Int32. Parse () throws an exception, Int32.TryParse () does not throw an exception, and returns TRUE or false to indicate whether the resolution was successful. If parsing an error, the out call will get a value of 0;
In terms of performance, int32.tryparse () is better than Int32.Parse () and Int32.Parse () is better than Convert.ToInt32 ().
Suggestion: in. NET1.1 under Int32.Parse (); NET2.0 with Int32.TryParse ().


Supplements

The code is as follows Copy Code

Acquiring the location code of Chinese characters
byte[] array = new BYTE[2];
Array = System.Text.Encoding.Default.GetBytes ("Ah");



int i1 = (short) (Array[0]-"");
int i2 = (short) (Array[1]-"");


Chinese character code under the Unicode decoding method
Array = System.Text.Encoding.Unicode.GetBytes ("Ah");
I1 = (short) (Array[0]-"');
I2 = (short) (Array[1]-"');


Unicode reverse decoding to Chinese characters
String str = "4a55";
string S1 = str. Substring (0,2);
string s2 = str. Substring (2,2);


int T1 = Convert.ToInt32 (s1,16);
int t2 = Convert.ToInt32 (s2,16);


Array[0] = (byte) t1;
ARRAY[1] = (byte) t2;


string s = System.Text.Encoding.Unicode.GetString (array);


Default mode reverse decoding for Chinese characters
Array[0] = (byte) 196;
ARRAY[1] = (byte) 207;
s = System.Text.Encoding.Default.GetString (array);


Take string length
s = "Iam side gun gun";
int len = S.length;//will output as 6
byte[] Sarr = System.Text.Encoding.Default.GetBytes (s);
Len = Sarr. Length;//will Output as 3+3*2=9


string addition
System.Text.StringBuilder sb = new System.Text.StringBuilder ("");
Sb. Append ("I");
Sb. Append ("AM");
Sb. Append ("square Gun");

/////////////////////////////////////////////////////////////////////



String--> byte array

Byte[] Data=syste.text.encoding.ascii.getbytes (string);

String--> byte

BYTE data = Convert.tobyte (string);

Byte[]-->string

String string = Encoding.ASCII.GetString (bytes, 0, nbytessize);

Reverse Reverse output

String str = Console.ReadLine ();
for (int i = str. Length-1; I >= 0; i--)
{
Console.Write (Str[i]);
}
Console.ReadLine ();

Common features for string handling

The code is as follows Copy Code

* Calculate the length of the string *

String myString = "This is a test!";
Console.WriteLine ("Text is: {0}", myString)
Console.WriteLine ("Text ' long is: {0}", Mystring.length)

* Conversion Case *

myString = Mystring.tolower (); Convert all characters to lowercase
myString = Mystring.toupper (); Convert all characters to uppercase

* Delete before and after space *

myString = Mystring.trim (); To delete a space before and after a string
Char[] TrimChars = {', ' e ', ' s '}; Characters ready for deletion
myString = Mystring.trim (trimChars); Delete all specified characters
myString = Mystring.trimend (); Remove a space after a string
myString = Mystring.trimstart (); To delete a space before a string

* Add spaces *

myString = Mystring.padright (14, ""); When the string is not 14 digits long, fill it with the specified character on his right
myString = Mystring.padleft (14, ""); When the string is less than 14 bits long, fill it with the specified character on his left

* Split String *

string[] Nstrs = Mystring.split (', 3); Split by Space and return the first three strings


* Get substring *

String a = Mystring.substring (2,2); Gets two characters starting at the third bit of the mystring string because the index start bit is 0

* Replace the character in the string *

String a = Mystring.replace ("i", "O"); Replace All "I" in this string with "O"


The string in C # is actually a reading group of char variables. You can access each character in the string in the following way, but you cannot modify them.

String myString = "This is a test!";
foreach (char mychar in myString)
{
Console.Write ("{0}", MyChar);
}

To get a read-write array of characters, you can do so.

char[] Mychars = Mystring.tochararray ();

A representation method for special characters

Because double quotes are used in C # to break the start and end of a string, for special characters, such as double quotes themselves, you need to use auxiliary characters called escape characters to represent

Common operations such as comparisons of strings

1. String comparison

  code is as follows copy code
string.compare (x,y); The
<0:x is less than Y. or x is a null reference. The
=0:x equals Y. The
>0:x is greater than Y. Or y is a null reference.
String. Equals (X,y);
true x equals Y.
False x is unequal to Y.
2. Extract substring from string
The StringBuilder class does not have a method that supports substrings, so it must be extracted with the string class.
String mystring= "My name is Ynn."; The
//displays "name is Ynn."
Console.WriteLine (mystring. Substring (3));
//displays "Ynn"
Console.WriteLine (mystring. Substring (11,3));

3. Format number
C, c         currency format.
D, d         decimal format.
E, e         scientific count (exponential) format.
F, f         fixed point format.
G, g         General format.
N, n         number format.
R, r         round-trip format to ensure that a number converted to a string is converted back to a number with the same value as the original number.
x, x         hexadecimal format.

  code is as follows copy code
double val= Math.PI;
Console.WriteLine (Val. ToString ());   //displays 3.14159265358979
Console.WriteLine (val). ToString ("E"));//displays 3.141593E+000
Console.WriteLine (val. ToString ("F3");//displays 3.142
int val=65535;
Console.WriteLine (Val. ToString ("x"));   //displays FFFF
Console.WriteLine (val). ToString ("X"));   //displays FFFF
Single val=;
Console.WriteLine (Val. ToString ("P"));   //displays 12.30%
Console.WriteLine (val. ToString ("P1"));   //displays 12.3%

The default formatting puts a space between the number and the percent semicolon. The customization method is as follows:
Where the NumberFormatInfo class is a member of the System.Globalization namespace, the namespace must be imported into the program.

The code is as follows Copy Code
Single val=;
Object Myobj=numberformatinfo.currentinfo.clone () as NumberFormatInfo;
NumberFormatInfo Myformat=myobj as NumberFormatInfo;
MyFormat. Percentpositivepattern=1;
Console.WriteLine (Val. ToString ("P", MyFormat)); Displays 12.3%;
Console.WriteLine (Val. ToString ("P1", MyFormat)); Displays 12.3%;

Formatting has a lot of flexibility. The following example shows a money structure that is meaningless:

The code is as follows Copy Code
Double val=1234567.89;
int [] groupsize={2,1,3};
Object Myobj=numberformatinfo.currentinfo.clone ();
NumberFormatInfo Mycurrency=myobj as NumberFormatInfo;
Mycurrency. Currencysymbol= "#"; Symbol
Mycurrency. Currencydecimalseparator= ":"; Decimal point
Mycurrency.    Currencygroupseparator= "_"; Separator
Mycurrency. Currencygroupsizes=groupsize;
Output #1_234_5_67:89
Console.WriteLine (Val. ToString ("C", mycurrency));

The last class, take a look at it slowly.

The code is as follows Copy Code


Using System;


Namespace Teststringapp
{
<summary>
Summary description of the CLASS1.
</summary>
Class Class1
{
<summary>
The main entry point for the application.
</summary>
[STAThread]
static void Main (string[] args)
{
//
TODO: Add code here to start the application
//
Assign a value directly to a string
String stra = "This is a string";
Console.WriteLine ("Stra:" +stra);
ToCharArray method, create char array; IndexOf method, find substring position
char[] Chararray = Stra.tochararray (0,stra.indexof ("string"));
Initializes a string using the New keyword, which is equivalent to chararray.tostring ()
String strb = new string (Chararray);
Console.WriteLine ("STRB:" +STRB);
Insert method, inserting substring
String strc = Stra.insert (Stra.indexof ("string"), "another");
Console.WriteLine ("STRC:" +STRC);
+ operator, connection string
String strd = Stra + strb;
Console.WriteLine ("STRD:" +STRD);
String.Concat method, link string, equivalent +
String.Equals method, comparing strings, equals = =
if (String.Equals (Strd,string.concat (STRA,STRB))
{
if (strd = = STRA+STRB)
{
Console.WriteLine ("String.Concat equivalent to +/n,system.equals equals = =");
}
}
Trim method, removing spaces or other characters from a string
String stre = Stra.trim ();
Console.WriteLine ("Stre:" +stre);
Use/Display Quotes "and backslashes/
String strf = "c://windows//system32//";
Console.WriteLine ("/" "+ strf +"/"");
Use @ Show quotes and backslashes/
String STRG = @ "c:/windows/system32/";
Console.WriteLine (@ "" "" + STRG + @ "" ");
String converted to int type
String strh = "12345";
int theint = Int. Parse (STRH);
Console.WriteLine ("Scientific count shows integer {0:e}", Theint);
Console.WriteLine ("Hexadecimal display integer {0:x}", Theint);
String converted to float type
String stri = "123.45";
float thefloat = float. Parse (Stri);
Console.WriteLine ("Show floating-point number, specify decimal places {0:f4}", thefloat);
Console.ReadLine ();
}
}
}

1) Intercept string
Using the substring method, the method has two overloaded functions in C #: substring (parameter), substring (parameter 1, parameter 2), as follows:

The code is as follows Copy Code
String A = "I ' m a string";
Sting b=a.substring (1);
Sting c=a.substring (1,6);

Where parameter 1 passed in is the starting position of the string, the character subcode string B intercepts all characters after the 2nd character of string A.
The character subcode string C will intercept the length 6 after the 2nd character of string A.
The argument must be greater than or equal to 0, and a argumentOutOfRange exception will be thrown if less than 0.
2) string into a character array
First, a string type variable can be viewed as a read-only group of char variables, so that each character can be accessed using the following syntax:
String A = "I ' m a string"
Char B =a[1];
If you turn a string into a writable char array, you can use the ToCharArray () method:
char [] = A.tochararray ();
Use B.length to get the length of the string.
3) Conversion case
<string>. ToLower () Convert to lowercase
<string>. ToUpper () converted to uppercase
4 Delete A string of spaces or a specified character
To delete a space before and after a string:
<string>. Trim ()
To delete a specified character:
First, use the char array to specify a specific character
char[] C ={', ' E ',}
<string>. Trim (C)
You can also use TrimStart (), TrimEnd () to remove the spaces before and after, or the specified characters.
5 Add a space or a specified character before and after the string
<string>. PadLeft (parameter) <string> PadRight (parameter) parameter is the length of the string after the space is added
<string>. PadLeft (parameter 1, parameter 2) parameter 1 is the length that the string is reached, and parameter 2 is the character that is added.
6) use of indexof ()
IndexOf ()
Finds the first occurrence of a specified character or string in a string, returning the first index value, such as:
Str1. IndexOf ("word");//Find the index value (position) of the word in str1
Str1. IndexOf ("string");//Find the index value (position) of the first character of the string in str1
Str1. IndexOf ("word", start,end)//from str1 start+1 characters, find the end character, find the position of "word" in the string STR1 [from the first character] Note: Start+end cannot be greater than the length of str1
7 Use of Insert ()
<string>.insert (parameter 1, parameter 2)
Parameter 1 is the position in which the substring is inserted, and parameter 2 is the substring to insert
8 Compare the size of the string
Compare (STR1,STR2)--Compare the size of the two string str1,str2, if greater than the return positive number, equal to 0, less than the return negative
9) Replace the specified string
String.Replace (parameter 1, parameter 2)--replaces the specified character in the string with the specified character
There are a lot of ways to handle strings, here are not listed, and later used to learn slowly.

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.