在C#中返回字符串第一个单词的最佳方法是什么?
基本上,如果字符串是"hello world"
,我需要获取"hello"
。
谢谢
发布于 2010-08-31 16:30:48
您可以组合使用Substring
和IndexOf
。
var s = "Hello World";
var firstWord = s.Substring(0,s.IndexOf(" "));
但是,如果输入字符串只有一个单词,这将不会给出预期的单词,因此需要一个特殊情况。
var s = "Hello";
var firstWord = s.IndexOf(" ") > -1
? s.Substring(0,s.IndexOf(" "))
: s;
发布于 2010-08-31 16:35:05
您可以尝试:
string s = "Hello World";
string firstWord = s.Split(' ').First();
Ohad Schneider's注释是正确的,所以您可以简单地请求First()
元素,因为总会有至少一个元素。
有关使用First()
还是FirstOrDefault()
的更多信息,您可以了解更多here
发布于 2010-08-31 16:34:15
一种方法是在字符串中查找空格,并使用空格的位置来获得第一个单词:
int index = s.IndexOf(' ');
if (index != -1) {
s = s.Substring(0, index);
}
另一种方法是使用正则表达式来查找单词边界:
s = Regex.Match(s, @"(.+?)\b").Groups[1].Value;
https://stackoverflow.com/questions/3607310
复制相似问题