ppo*_*zos 47
你可以试试:
string s = "Hello World";
string firstWord = s.Split(' ').First();
Run Code Online (Sandbox Code Playgroud)
Ohad Schneider的评论是正确的,所以你可以简单地询问First()元素,因为总会有至少一个元素.
有关是否使用的更多信息,First()或者FirstOrDefault()您可以在此处了解更多信息
Jam*_*iec 24
您可以使用的组合Substring和IndexOf.
var s = "Hello World";
var firstWord = s.Substring(0,s.IndexOf(" "));
Run Code Online (Sandbox Code Playgroud)
但是,如果输入字符串只有一个单词,则不会给出预期的单词,因此需要特殊情况.
var s = "Hello";
var firstWord = s.IndexOf(" ") > -1
? s.Substring(0,s.IndexOf(" "))
: s;
Run Code Online (Sandbox Code Playgroud)
一种方法是在字符串中查找空格,并使用空格的位置来获取第一个单词:
int index = s.IndexOf(' ');
if (index != -1) {
s = s.Substring(0, index);
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用正则表达式来查找单词边界:
s = Regex.Match(s, @"(.+?)\b").Groups[1].Value;
Run Code Online (Sandbox Code Playgroud)