计算字符串C#中的单词和空格

时间:2013-07-23 14:07:09

标签: c# winforms visual-studio-2010

我想计算字符串中的单词和空格。字符串看起来像这样:

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

我还应该做些什么来计算空格?

10 个答案:

答案 0 :(得分:30)

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

请注意,使用Char.IsWhiteSpace假定除" "之外的其他字符为空格(如newline)。看一下备注部分,看看究竟是哪一个。

答案 1 :(得分:2)

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

获得字符串数组时,元素数是单词数,空格数是单词数-1

答案 2 :(得分:1)

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

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

答案 3 :(得分: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循环也可以使用正则表达式完成:How do I replace multiple spaces with a single space in C#?

答案 4 :(得分: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;
    }

答案 5 :(得分:0)

除了蒂姆的参赛作品,如果你在两边都有填充,或者在彼此旁边有多个空格:

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

答案 6 :(得分:0)

这是使用正则表达式的方法。还有别的东西需要考虑。如果你有很多不同类型的空格的长字符串会更好。与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。

答案 7 :(得分: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();
    }
}

答案 8 :(得分:0)

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

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

答案 9 :(得分: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);