one, instantiate a string object
1, the most common method is to directly assign a string to a string variable.
Note 1: The escape character \, the string contains quotation marks "", backslash \ or newline, etc. all need to use "\" output.
Note 2: Use the @ symbol in front of the string to indicate that the escape sequence is not processed.
1 stringstring1 ="This was a string created by assignment.";2 Console.WriteLine (string1);3 stringSTRING2A ="The path is C:\\publicdocuments\\report1.doc";4 Console.WriteLine (STRING2A);5 stringSTRING2B =@"The path is C:\PublicDocuments\Report1.doc";6 Console.WriteLine (string2b);7 //Show Results:8 //This was a string created by assignment.9 //The path is C:\PublicDocuments\Report1.docTen //The path is C:\PublicDocuments\Report1.doc
2. Use the string constructor.
We can instantiate an array of Unicode characters using:
string ( char[]) string (char*) String (sbyte*)
Or you could repeat a character over and over again by instantiating it:
String (Char, Int32)
Furthermore, the instantiation of a subset of a Unicode character array is used:
String (char*, Int32, Int32) String (char[], Int32, Int32) String (sbyte*, Int32, Int32)
1 Char[] chars = {'W','o','R','D' };2 sbyte[] bytes = {0x41,0x42,0x43,0x44,0x45,0x00 };3 4 //instantiates a string by a character array.5 stringstring1 =New string(chars);6 Console.WriteLine (string1);7 8 stringStringfrombytes =NULL;9 stringStringfromchars =NULL;Ten unsafe One { A fixed(sbyte* Pbytes =bytes) - { - //instantiates a string with a byte array pointer. theStringfrombytes =New string(pbytes); - } - fixed(Char* Pchars =chars) - { + //instantiates a string with a character array pointer. -Stringfromchars =New string(pchars); + } A } at Console.WriteLine (stringfrombytes); - Console.WriteLine (stringfromchars); - - //instantiates a string consisting of 20 C. - stringstring2 =New string('C', -); - Console.WriteLine (string2); in - //instantiates a string with a length of 2 from the 1th letter in the character array (starting at 0) to stringString3 =New string(Chars,1,2); + Console.WriteLine (string3); - //Show Results: the //Word * //ABCDE $ //WordPanax Notoginseng //CCCCCCCCCCCCCCCCCCCCC - //or
Second, String class properties
- Chars gets The Char object at the specified position in the current String object .
- Length gets the number of characters in the current string object, that is, the string length.
1 stringSTR1 ="Test";2 for(intCTR =0; Ctr <= str1. Length-1; ctr++)3Console.Write ("{0}", str1[ctr]);4 //Show Results:5 //T e s t
Reference: Http://msdn.microsoft.com/zh-cn/library/chfa2zb8 (vs.80). aspx
Use of String class and Method in C # (i)