C# 2.0 function to get Second Word from string [closed]

To get the part of the string after the first space:

string city = str.Substring(str.IndexOf(' ') + 1);

This will also give a result even if there happens to be no space in the string. The IndexOf method will return -1 in that case, so the code will return the entire string. If you would want an empty string or an exception in that case, then you would get the index into a variable first so that you can check the value:

string city;
int index = str.IndexOf(' ');
if (index == -1) {
  throw new ArgumentException("Unable to find a space in the string.");
} else {
  city = str.Substring(index + 1);

Browse More Popular Posts

Leave a Comment