2017-02-08 6 views
-2

私はこのプログラムで言葉を数えようとしていますが、なぜプログラムが1よりも少ない数を数えているのか分かりません。例えばC#はカウントを理解できません

日はホット

プログラムは唯一の2ワードがあることを私が表示されますです。

Console.WriteLine("enter your text here"); 
string text = Convert.ToString(Console.ReadLine()); 
int count = 0; 
text = text.Trim(); 
for (int i = 0; i < text.Length - 1; i++) 
{ 
    if (text[i] == 32) 
    { 
     if (text[i + 1] != 32) 
     { 
      count++; 
     } 
    } 
} 
Console.WriteLine(count); 
+3

あなたはスペースを数えています。 – DavidG

+0

デバッグを試しましたか? –

+1

'string.Split'メソッドに興味があるかもしれません。 – juharr

答えて

1
if (text[i] == 32) 

あなたは、スペースではなく、言葉

を数えている。ここ正規表現は、このための最善の作品MatchCollection

using System.Text.RegularExpressions; 

namespace StackOverCSharp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("enter your text here"); 
      string text = Convert.ToString(Console.ReadLine()); 
      MatchCollection collection = Regex.Matches(text, @"[\S]+"); 

      Console.WriteLine(collection.Count); 
     } 
    } 
} 
2

を使用して、より良い解決策です。

var str = "this,is:my test string!with(difffent?.seperators"; 
int count = Regex.Matches(str, @"[\w]+").Count; 

結果は、彼らが繰り返すか、ない場合に関わらず、スペースや特殊文字が含まれていない、8 カウントすべての単語です。

+0

単語が「英数字以外の英数字」の場合、正しい解決策(+1)です。 *自然言語*(英語、ロシア語など)の単語は、非常に複雑なものです。 "できません" - 1つの単語、 "できません" - 2つ。 "忘れないでください" - 1つ、 "私を忘れないでください" - 4つなど –

関連する問題