【问题标题】:Count words and spaces in string C#计算字符串 C# 中的单词和空格
【发布时间】:2013-07-22 15:54:54
【问题描述】:

我想计算字符串中的单词和空格。字符串如下所示:

Command do something ptuf(123) and bo(1).ctq[5] v:0,

到目前为止,我有类似的东西

int count = 0;
string mystring = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
foreach(char c in mystring) 
{
if(char.IsLetter(c)) 
  {
     count++;
  }
}

我还应该如何计算空格?

【问题讨论】:

  • 你说数单词,但你在数字母。这是你想要的吗?
  • 不是文字,是字符。
  • 你说得对,我的代码出错了。我想数单词。对不起。
  • 两个连续的空格字符算1还是2?

标签: c# winforms visual-studio-2010


【解决方案1】:

你可以使用带空格的 string.Split http://msdn.microsoft.com/en-us/library/system.string.split.aspx

当你得到一个字符串数组时,元素的个数就是单词的个数,空格的个数就是单词的个数-1

【讨论】:

    【解决方案2】:
    int countSpaces = mystring.Count(Char.IsWhiteSpace); // 6
    int countWords = mystring.Split().Length; // 7
    

    请注意,两者都使用Char.IsWhiteSpace,它将" " 以外的其他字符假定为空格(如newline)。看看备注部分,看看到底是哪个。

    【讨论】:

    • 大声笑....如果我在编写我的这些方法时刚刚理解 linq....顺便说一句,当有两个连续空格时,它会消除单词吗?
    • @Daniel:不,如果存在两个并发空间,那将包括“幽灵”词。
    • @Daniel:不,如果您不提供拆分字符,则假定为空格。
    • @user2366842:您可以使用mystring.Split().Count(word => !String.IsNullOrEmpty(word));Split 重载StringSplitOptions.RemoveEmptyEntries。后者的问题是您不能再使用隐式Char.IsWhiteSpace 测试,它也会被其他字符(如Environment.NewLine 或制表符)分割。这就是为什么我更喜欢第一种方法,即使它效率不高。
    • 如果显式传递null 或空数组(如mystring.Split(new char[0], StringSplitOptions.RemoveEmptyEntries).Length;),当您使用采用StringSplitOptions 的重载时,您仍然可以获得char.IsWhiteSpace 行为
    【解决方案3】:

    如果你想计算空格,你可以使用 LINQ:

    int count = mystring.Count(s => s == ' ');
    

    【讨论】:

    • 从技术上讲,您必须添加 +1。 "a b c".Count(x => x == ' ') = 2 当有 3 个单词时。
    • 做什么?那只是为了计算空间
    【解决方案4】:

    我已经准备好一些代码来获取字符串中的单词列表: (扩展方法,必须在静态类中)

        /// <summary>
        /// Gets a list of words in the text. A word is any string sequence between two separators.
        /// No word is added if separators are consecutive (would mean zero length words).
        /// </summary>
        public static List<string> GetWords(this string Text, char WordSeparator)
        {
            List<int> SeparatorIndices = Text.IndicesOf(WordSeparator.ToString(), true);
    
            int LastIndexNext = 0;
    
    
            List<string> Result = new List<string>();
            foreach (int index in SeparatorIndices)
            {
                int WordLen = index - LastIndexNext;
                if (WordLen > 0)
                {
                    Result.Add(Text.Substring(LastIndexNext, WordLen));
                }
                LastIndexNext = index + 1;
            }
    
            return Result;
        }
    
        /// <summary>
        /// returns all indices of the occurrences of a passed string in this string.
        /// </summary>
        public static List<int> IndicesOf(this string Text, string ToFind, bool IgnoreCase)
        {
            int Index = -1;
            List<int> Result = new List<int>();
    
            string T, F;
    
            if (IgnoreCase)
            {
                T = Text.ToUpperInvariant();
                F = ToFind.ToUpperInvariant();
            }
            else
            {
                T = Text;
                F = ToFind;
            }
    
    
            do
            {
                Index = T.IndexOf(F, Index + 1);
                Result.Add(Index);
            }
            while (Index != -1);
    
            Result.RemoveAt(Result.Count - 1);
    
            return Result;
        }
    
    
        /// <summary>
        /// Implemented - returns all the strings in uppercase invariant.
        /// </summary>
        public static string[] ToUpperAll(this string[] Strings)
        {
            string[] Result = new string[Strings.Length];
            Strings.ForEachIndex(i => Result[i] = Strings[i].ToUpperInvariant());
            return Result;
        }
    

    【讨论】:

      【解决方案5】:

      除了 Tim 的条目之外,如果您在任一侧有填充,或者彼此相邻有多个空格:

      Int32 words = somestring.Split(           // your string
          new[]{ ' ' },                         // break apart by spaces
          StringSplitOptions.RemoveEmptyEntries // remove empties (double spaces)
      ).Length;                                 // number of "words" remaining
      

      【讨论】:

        【解决方案6】:

        这是一个使用正则表达式的方法。只是要考虑其他事情。如果你有很多不同类型的空格的长字符串会更好。类似于 Microsoft Word 的 WordCount。

        var str = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
        int count = Regex.Matches(str, @"[\S]+").Count; // count is 7
        

        为了比较,

        var str = "Command     do    something     ptuf(123) and bo(1).ctq[5] v:0,";
        

        str.Count(char.IsWhiteSpace) 为 17,而正则表达式计数仍为 7。

        【讨论】:

        • 有些人在遇到问题时会想“我知道,我会使用正则表达式”。现在他们有两个问题。
        • @BradChristie 我觉得你在滥用这句话。我不是在这里写某种解析器。它只匹配非空白文本,然后你得到计数。它不计算连续的空格,完成后不需要清理集合。表达式本身是你能得到的最基础的。这并不难理解或维护。我不喜欢我做错事的感觉,所以你能解释一下为什么你认为这句话适用于这个解决方案吗?
        • 正则表达式在某些情况下很有用,只要它保持简单(这个是)并且易于维护(似乎是)它应该没问题。当你开始过度使用它并制作一个 15 行长的正则表达式来过滤掉你的电子邮件地址时,你就会开始遇到问题。
        • 我想我只是在暗示正则表达式对于“简单”字符串操作来说太过分了。这里没有真正的模式处理,复杂的询问或复杂的算法。字符串库已经有解决这个问题的实现。话虽如此,使用" foo ".Trim()Regex.Replace(" foo ", @"^\s+|\s+$", String.Empty) 有意义吗?根据您的定义,后者简单且易于维护,但考虑到 Trim 存在,它(恕我直言)完全矫枉过正。
        • @BradChristie 我知道 trim() 显然更容易理解/更快/等等,但考虑到所选答案甚至不考虑背靠背空格的事实,而你的答案没有'不考虑除空格之外的任何空格。可能这个应用程序只需要您发布的内容或所选答案的功能,但正则表达式解决方案对我来说似乎更强大 - 并不完美,但比任何一个都更接近。
        【解决方案7】:

        这将考虑到:

        • 以空格开头或结尾的字符串。
        • 双/三/...空格。

        假设唯一的单词分隔符是空格并且你的字符串不为空。

        private static int CountWords(string S)
        {
            if (S.Length == 0)
                return 0;
        
            S = S.Trim();
            while (S.Contains("  "))
                S = S.Replace("  "," ");
            return S.Split(' ').Length;
        }
        

        注意:while 循环也可以使用正则表达式来完成:How do I replace multiple spaces with a single space in C#?

        【讨论】:

        • 你知道.Split有一个接受StringSplitOptions的重载,可以指定RemoveEmptyEntries.Trim() & .Replace 是多余的。
        【解决方案8】:
        using namespace;
        namespace Application;
        class classname
        {
            static void Main(string[] args)
            {
                int count;
                string name = "I am the student";
                count = name.Split(' ').Length;
                Console.WriteLine("The count is " +count);
                Console.ReadLine();
            }
        }
        

        【讨论】:

        • 请不要发布仅代码的答案,但请解释您的代码的作用。
        【解决方案9】:

        如果您需要空格计数,请尝试此操作。

        string myString="I Love Programming";
        var strArray=myString.Split(new char[] { ' ' });
        int countSpace=strArray.Length-1;
        

        【讨论】:

          【解决方案10】:

          间接呢?

          int countl = 0, countt = 0, count = 0;
          
          foreach(char c in str) 
          {
              countt++;
              if (char.IsLetter(c)) 
              {
                  countl++;
              }
          }
          count = countt - countl;
          Console.WriteLine("No. of spaces are: "+count);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-03-31
            • 2012-09-21
            • 2020-08-08
            • 2012-09-23
            • 1970-01-01
            • 2023-03-21
            相关资源
            最近更新 更多