C#2.0函数从字符串中获取第二个字

Man*_*ngh -6 c# string substring

我需要编写一个函数,它将在第一个单词(第一个空格)之后返回给我.

例如,我在C#2.0中得到了以下字符串.

string str = "M000. New Delhi"
Run Code Online (Sandbox Code Playgroud)

现在我想编写一个函数,如果str通过则返回"新德里" .

请建议!!

Guf*_*ffa 8

要在第一个空格后获取字符串的一部分:

string city = str.Substring(str.IndexOf(' ') + 1);
Run Code Online (Sandbox Code Playgroud)

即使字符串中没有空格,这也会产生结果.在这种情况下,该IndexOf方法将返回-1,因此代码将返回整个字符串.如果您希望在这种情况下使用空字符串或异常,那么您将首先将索引转换为变量,以便您可以检查值:

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);
}
Run Code Online (Sandbox Code Playgroud)