Friday, January 20, 2017

C# Substrings

Anyone who has worked with strings in C# is probably familiar with the Substring function. For example, if we want to get the first three characters of a string we could do this:

string s = text.Substring(0,3);
or to get characters 3 and 4:
string s = text.Substring(2,2);
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);
We can also use Substring to get a single character but there are actually some lesser known ways of doing this.
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:
char c = text[2];
This method could also be used to iterate through all the characters in a string:
for(int i=0; i<text.Length; i++) {
   char c = text[i];
   // Do something with c 
}
but there is an even simpler way to handle this:
foreach(char c in text)
{
     // Do something with c 
}
This last method is a much cleaner way to iterate through all the characters in a string.

3 comments:

Shalini said...
This comment has been removed by a blog administrator.
Unknown said...
This comment has been removed by a blog administrator.
Unknown said...
This comment has been removed by a blog administrator.