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.IsWhiteSpace以外の文字を想定して which を使用することに注意してください( のように)。備考セクションを見て、正確にどれを確認してください。" "newline

于 2013-07-23T14:10:37.787 に答える
2

スペースを数えたい場合は、LINQ を使用できます。

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

これには次の点が考慮されます。

  • スペースで開始または終了する文字列。
  • ダブル/トリプル/... スペース。

唯一の単語セパレーターがスペースであり、文字列が null ではないことを前提としています。

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

ティムのエントリに加えて、どちらかの側にパディングがある場合、または複数のスペースが隣り合っている場合:

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

文字列内の単語のリストを取得する準備が整ったコードがいくつかあります: (拡張メソッド、静的クラスにある必要があります)

    /// <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 に答える