Manipulating strings
Because String is immutable, all the methods that “manipulate” a string return a
new one, leaving the original untouched (the same goes for when you reassign a
string variable).
Substring extracts a portion of a string:
string left3 = "12345".Substring (0, 3); // left3 = "123";
string mid3 = "12345".Substring (1, 3); // mid3 = "234";
If you omit the length, you get the remainder of the string:
string end3 = "12345".Substring (2); // end3 = "345";
Insert and Remove insert or remove characters at a specified position:
string s1 = "helloworld".Insert (5, ", "); // s1 = "hello, world"
string s2 = s1.Remove (5, 2); // s2 = "helloworld";
PadLeft and PadRight pad a string to a given length with a specified character (or a
space if unspecified):
Console.WriteLine ("12345".PadLeft (9, '*')); // ****12345
Console.WriteLine ("12345".PadLeft (9)); // 12345
If the input string is longer than the padding length, the original string is returned
unchanged.
TrimStart and TrimEnd remove specified characters from the beginning or end of a
string; Trim does both. By default, these functions remove whitespace characters
(including spaces, tabs, new lines, and Unicode variations of these):
Console.WriteLine (" abc \t\r\n ".Trim().Length); // 3
Replace replaces all occurrences of a particular character or substring:
Console.WriteLine ("to be done".Replace (" ", " | ") ); // to | be | done
Console.WriteLine ("to be done".Replace (" ", "") ); // tobedone
ToUpper and ToLower return upper- and lowercase versions of the input string. By
default, they honor the user’s current language settings; ToUpperInvariant and
ToLowerInvariant always apply English alphabet rules.
No comments:
Post a Comment