【问题标题】:left string function in C#C#中的左字符串函数
【发布时间】:2010-08-31 08:29:10
【问题描述】:

在 C# 中返回字符串的第一个单词的最佳方法是什么?

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

谢谢

【问题讨论】:

  • 空格是您想要分隔单词的唯一字符吗?制表符、换行符和回车符呢?
  • 扩展 cwap 的评论:标点符号呢? “你好,世界”?

标签: c# string


【解决方案1】:

你可以试试:

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

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

有关是否使用First()FirstOrDefault() 的更多信息,您可以了解更多here

【讨论】:

  • 小幅改进:使用 String.Split 的重载,因为除了第一部分之外,您不关心所有内容。
  • 你不需要FirstOrDefault,总会有至少一个元素,所以你可以写First(即使没有空格你会得到整个字符串)。跨度>
  • 你的解决方案是对的,没必要“尝试”。
  • 为什么要涉及 Linq?如果总是有一个元素并且您首先使用,只需通过索引器访问它:string firstWord = s.Split(' ')[0];
  • 请注意,最大分割部分(如果使用)应该是 2 而不是 1:theString.Split(new char []{ ' ', '\t'}, 2).First();
【解决方案2】:

您可以使用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;

【讨论】:

  • 如果字符串只包含一个单词,我会添加一个特殊情况,例如如果 IndexOf 返回 -1。
【解决方案3】:

一种方法是在字符串中寻找一个空格,利用空格的位置来获取第一个单词:

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

另一种方法是使用正则表达式来查找单词边界:

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

【讨论】:

    【解决方案4】:

    如果您只想在空格上拆分,answer of Jamiec 是最有效的。但是,为了多样化,这里有另一个版本:

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

    作为奖励,这也将识别all kinds of exotic whitespace characters 并忽略多个连续的空白字符(实际上它会从结果中修剪前导/尾随空白)。

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

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

    【讨论】:

      【解决方案5】:

      无耻地从 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];
      }
      

      【讨论】:

        【解决方案6】:

        处理各种不同的空白字符、空字符串和单个单词的字符串。

        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();
        }

        【讨论】:

          【解决方案7】:

          不要对所有字符串执行Split将拆分限制为 2。使用将计数作为参数的重载。使用String.Split Method (Char[], Int32)

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

          Split 将始终返回一个包含至少一个元素的数组,因此.[0]First 就足够了。

          【讨论】:

            【解决方案8】:

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

                    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;
                    }
                }
            

            【讨论】:

              【解决方案9】:
              string words = "hello world";
              string [] split = words.Split(new Char [] {' '});
              if(split.Length >0){
               string first = split[0];
              }
              

              【讨论】:

                猜你喜欢
                • 2012-07-16
                • 1970-01-01
                • 2013-12-22
                • 2012-03-15
                • 1970-01-01
                • 2021-10-21
                • 2011-03-25
                • 2012-03-26
                • 1970-01-01
                相关资源
                最近更新 更多