or to get characters 3 and 4:
string s = text.Substring(0,3);
Only slightly less known is that if you want to get the end of a string you can omit the length and just use the starting character. So to get everything from the 3rd character to the end of the string you can do this:
string s = text.Substring(2,2);
We can also use Substring to get a single character but there are actually some lesser known ways of doing this.
string s = text.Substring(2);
The first way is to use the fact that a string in C# can be treated as a character array. To get the third character you could do this:
This method could also be used to iterate through all the characters in a string:
char c = text[2];
but there is an even simpler way to handle this:
for(int i=0; i<text.Length; i++) {
char c = text[i];
// Do something with c
}
This last method is a much cleaner way to iterate through all the characters in a string.
foreach(char c in text)
{
// Do something with c
}
0 Komentar