11

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

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

我应该怎么做才能计算空间?

4

10 回答 10

35
int countSpaces = mystring.Count(Char.IsWhiteSpace); // 6
int countWords = mystring.Split().Length; // 7

请注意,两者都使用Char.IsWhiteSpacewhich 假定其他字符而不是" "空格(如newline)。看看备注部分,看看到底是哪个。

于 2013-07-23T14:10:37.787 回答
2

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

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

于 2013-07-23T14:10:05.053 回答
2

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

int count = mystring.Count(s => s == ' ');
于 2013-07-23T14:11:15.947 回答
1

这是使用正则表达式的方法。只是要考虑其他事情。如果你有很多不同类型的空格的长字符串会更好。类似于 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。

于 2013-07-23T14:16:38.707 回答
1

这将考虑到:

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

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

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 循环也可以使用正则表达式完成:如何在 C# 中用单个空格替换多个空格?

于 2013-07-23T14:28:46.747 回答
0

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

    /// <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;
    }
于 2013-07-23T14:12:55.453 回答
0

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

Int32 words = somestring.Split(           // your string
    new[]{ ' ' },                         // break apart by spaces
    StringSplitOptions.RemoveEmptyEntries // remove empties (double spaces)
).Length;                                 // number of "words" remaining
于 2013-07-23T14:14:35.310 回答
0
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();
    }
}
于 2015-03-13T18:29:09.900 回答
0

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

string myString="I Love Programming";
var strArray=myString.Split(new char[] { ' ' });
int countSpace=strArray.Length-1;
于 2019-12-03T11:36:22.137 回答
0

间接的呢?

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);
于 2021-06-22T07:07:47.930 回答