【发布时间】:2010-08-31 08:29:10
【问题描述】:
在 C# 中返回字符串的第一个单词的最佳方法是什么?
基本上如果字符串是"hello world",我需要得到"hello"。
谢谢
【问题讨论】:
-
空格是您想要分隔单词的唯一字符吗?制表符、换行符和回车符呢?
-
扩展 cwap 的评论:标点符号呢? “你好,世界”?
在 C# 中返回字符串的第一个单词的最佳方法是什么?
基本上如果字符串是"hello world",我需要得到"hello"。
谢谢
【问题讨论】:
你可以试试:
string s = "Hello World";
string firstWord = s.Split(' ').First();
Ohad Schneider's 评论是正确的,因此您可以简单地要求First() 元素,因为总会有至少一个元素。
有关是否使用First() 或FirstOrDefault() 的更多信息,您可以了解更多here
【讨论】:
String.Split 的重载,因为除了第一部分之外,您不关心所有内容。
FirstOrDefault,总会有至少一个元素,所以你可以写First(即使没有空格你会得到整个字符串)。跨度>
string firstWord = s.Split(' ')[0];
您可以使用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;
【讨论】:
一种方法是在字符串中寻找一个空格,利用空格的位置来获取第一个单词:
int index = s.IndexOf(' ');
if (index != -1) {
s = s.Substring(0, index);
}
另一种方法是使用正则表达式来查找单词边界:
s = Regex.Match(s, @"(.+?)\b").Groups[1].Value;
【讨论】:
如果您只想在空格上拆分,answer of Jamiec 是最有效的。但是,为了多样化,这里有另一个版本:
var FirstWord = "Hello World".Split(null, StringSplitOptions.RemoveEmptyEntries)[0];
作为奖励,这也将识别all kinds of exotic whitespace characters 并忽略多个连续的空白字符(实际上它会从结果中修剪前导/尾随空白)。
请注意,它也会将符号视为字母,因此如果您的字符串是Hello, world!,它将返回Hello,。如果不需要,则在第一个参数中传递一个分隔符数组。
但是,如果您希望它在世界上每种语言中都 100% 万无一失,那么它就会变得艰难......
【讨论】:
无耻地从 msdn 网站盗取 (http://msdn.microsoft.com/en-us/library/b873y76a.aspx)
string words = "This is a list of words, with: a bit of punctuation" +
"\tand a tab character.";
string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });
if( split.Length > 0 )
{
return split[0];
}
【讨论】:
处理各种不同的空白字符、空字符串和单个单词的字符串。
private static string FirstWord(string text)
{
if (text == null) throw new ArgumentNullException("text");
var builder = new StringBuilder();
for (int index = 0; index < text.Length; index += 1)
{
char ch = text[index];
if (Char.IsWhiteSpace(ch)) break;
builder.Append(ch);
}
return builder.ToString();
}
【讨论】:
不要对所有字符串执行Split,将拆分限制为 2。使用将计数作为参数的重载。使用String.Split Method (Char[], Int32)
string str = "hello world";
string firstWord = str.Split(new[]{' '} , 2).First();
Split 将始终返回一个包含至少一个元素的数组,因此.[0] 或First 就足够了。
【讨论】:
我在我的代码中使用了这个函数。它提供了将第一个单词或每个单词大写的选项。
public static string FirstCharToUpper(string text, bool firstWordOnly = true)
{
try
{
if (string.IsNullOrEmpty(text))
{
return text;
}
else
{
if (firstWordOnly)
{
string[] words = text.Split(' ');
string firstWord = words.First();
firstWord = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(firstWord.ToLower());
words[0] = firstWord;
return string.Join(" ", words);
}
else
{
return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text.ToLower());
}
}
} catch (Exception ex)
{
Log.Exc(ex);
return text;
}
}
【讨论】:
string words = "hello world";
string [] split = words.Split(new Char [] {' '});
if(split.Length >0){
string first = split[0];
}
【讨论】: