Starting from today, record the path of C #
C # Learning strings
The C # string is the reference type, and the non-variability and sealing are the two types of the string type. Once a string is created, it cannot be modified, all the modified strings only create a new string and return a reference to the new string.
The string type cannot be inherited.
string str = "my name is {0},I like {1},My age is{2}";
Console.WriteLine(string.Format(str,"minlecun","tudou","26"));
string str1 = "hello";
string str2 = " ";
string str3 = "world";
Console.WriteLine(string.Concat(str1, str2, str3));
You can traverse strings like arrays.
String thestring = "Hello, world ";
Char thefristchar = thestringp [0];
The characters are read-only and cannot be modified.
String thestring = "Hello, world ";
Thestring [0] = 's'; // wrong
- Similar to an array, you can use length to obtain the string length.
- You can use foreach to traverse strings.
string theString = "hi,world";
foreach(char s in theString)
{
Console.Write(s);
}
- You can use tochararray () to obtain the character array representing the string.
string theString = "hello World";
char[] theChars = theString.ToCharArray();
- Trim removes two leading spaces, trimstart removes the starting string, and trimend removes the ending string.
string s = "aaasssddd";
string s1 = "asasasddd";
Console.WriteLine(s.TrimStart(new char[] {'a','s'})); //ddd.
Console.WriteLine(s1.TrimStart(new char[] {'a','s'})); //sasasddd.
- Padleft or padright adds the specified character at the beginning and end
string s = "12345";
Console.WriteLine(s.PadLeft(10,'v')); //vvvvv12345
string s = "12345";
Console.WriteLine(s.PadLeft(5,'v')); //12345
string s = "12345";
Console.WriteLine(s.PadLeft(3,'v')); //12345
- Split splits the string into string segments according to the specified characters and returns a string array.
string str = "one two_three=four";
string[] arr = str.Split(new char[] {' ','_','='});
foreach (string s in arr) {
Console.WriteLine(s);
}
- Substring can be used to obtain the string fragment from the specified position to the end. The first parameter is the starting position. The second parameter is the length of the truncated string.
string str="0123456789";
string newStr = str.Substring(3);
Console.WriteLine(newStr);
string newStr2 = str.Substring(3,1);
Console.WriteLine(newStr2);
- Repalce replaces the specified string
string str = "asdasdzxc";
Console.WriteLine(str.Replace('a', '1'));
- Remove Delete the string segment at the specified position in the string. The first parameter is the position. The second parameter is the length.
string str = "0123456789";
Console.WriteLine(str.Remove(5));
Console.WriteLine(str.Remove(5,1));
- Indexof finds the position of the specified string in the string. The first parameter is the starting position of the 2nd string parameters to be searched.
string str = "ok is ok";
Console.WriteLine(str.IndexOf("ok"));
Console.WriteLine(str.IndexOf("ok",1));