2010-08-31 124 views
15

返回C#中字符串的第一个单词的最佳方式是什么?C#中的左侧字符串函数#

基本上如果字符串是"hello world",我需要得到"hello"

感谢

+0

空格是你想分开单词的唯一字符吗?那么tab,换行符和回车呢? – cwap 2010-08-31 08:31:28

+0

延伸cwap的评论:标点怎么样? “你好,世界”? – lalli 2010-08-31 08:44:58

回答

19

您可以使用SubstringIndexOf的组合。

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; 
+6

如果字符串只包含一个单词,例如如果** IndexOf **返回-1。 – 2010-08-31 08:32:13

0
string words = "hello world"; 
string [] split = words.Split(new Char [] {' '}); 
if(split.Length >0){ 
string first = split[0]; 
} 
+0

split.Length。堆栈溢出不会让我编辑它。 – crh225 2017-09-07 15:12:01

8

一种方法是查找字符串中的空间,使用空间的位置,以获得的第一个字:

int index = s.IndexOf(' '); 
if (index != -1) { 
    s = s.Substring(0, index); 
} 

另一种方法是使用正则表达式寻找一个字边界:

s = Regex.Match(s, @"(.+?)\b").Groups[1].Value; 
35

你可以试试:

string s = "Hello World"; 
string firstWord = s.Split(' ').First(); 

Ohad Schneider's评论是正确的,所以你可以简单地要求First()元素,因为总会有至少一个元素。

有关是否使用First()或进一步信息FirstOrDefault()你可以学到更多here

+4

略微改进:对'String.Split'使用重载,因为您不关心除第一部分以外的所有内容,而是使用最大分割数。 – Richard 2010-08-31 09:11:04

+1

你不需要'FirstOrDefault',总会有至少一个元素,所以你可以直接写'First'(即使没有空间你会得到整个字符串)。 – 2015-03-30 15:23:30

+0

你的解决方案是正确的,没有必要“尝试”。 – Heinzi 2017-10-15 15:47:54

2

answer of Jamiec是最有效的,如果要拆分只对空间。但是,只是为了不同的缘故,这里的另一个版本:

var FirstWord = "Hello World".Split(null, StringSplitOptions.RemoveEmptyEntries)[0]; 

作为奖励,这也将认识到all kinds of exotic whitespace characters并忽略多个连续的空格字符(实际上这将削减从结果前/后空格) 。

请注意,它也会将符号计数为字母,所以如果您的字符串是Hello, world!,它将返回Hello,。如果你不需要,那么在第一个参数中传递一个分隔字符数组。

但是,如果你希望它是在世界上的每一种语言100%万无一失,那么它会变得艰难......

2

从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]; 
} 
1

无耻被盗处理各种不同的空白字符,空字符串和单个字符串。

​​
1

而不是做Split所有的字符串,限制你的分割数的2。使用以count为参数的过载。使用String.Split Method (Char[], Int32)

string str = "hello world"; 
string firstWord = str.Split(new[]{' '} , 2).First(); 

Split总是返回至少一个元素的数组所以无论是.[0]First就够了。

0

我在我的代码中使用了这个函数。它提供了一个选项,以大写第一个单词或每个单词。

 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; 
     } 
    } 
相关问题