2016-04-22 9 views
0

メソッドに文字列を渡すメソッドを作成しようとしていて、その文字列に含まれる単語の数を表示したいとします。文字列は、テキストボックスからのユーザー入力です。メソッドを表示できません。ワードカウンタ

private void button1_Click(object sender, EventArgs e) 
{ 
    countMethod(); 

} 
private string countMethod() 
{ 
    String text = textBox1.Text.Trim(); 
    int wordCount = 0, index = 0; 

    while (index < text.Length) 
    { 
     // check if current char is part of a word 
     while (index < text.Length && Char.IsWhiteSpace(text[index]) == false) 
      index++; 

     wordCount++; 

     // skip whitespace until next word 
     while (index < text.Length && Char.IsWhiteSpace(text[index]) == true) 
      index++; 
    } 
    return MessageBox.Show(wordCount.ToString()); 
} 

EDIT:

私は、メソッドに引数を追加しました。ループが完了したら、wordCountを文字列に送ります。私はそれを数回試して、それは動作します。私はプログラミングに慣れていないので、これがうまくいかない、あるいは別のやり方でやるべき理由がありますか?ありがとう

private void button1_Click(object sender, EventArgs e) 
{ 
    string userInput = textBox1.Text; 
    countMethod(userInput); 


} 
private string countMethod(string input) 
{ 
    string text = textBox1.Text.Trim(); 
    int wordCount = 0, index = 0; 

    while (index < text.Length) 
    { 
     // check if current char is part of a word 
     while (index < text.Length && Char.IsWhiteSpace(text[index]) == false) 
      index++; 

     wordCount++; 

     // skip whitespace until next word 
     while (index < text.Length && Char.IsWhiteSpace(text[index]) == true) 
      index++; 
    } 
    string total = wordCount.ToString(); 
    MessageBox.Show("The total words in this string are: " +total); 
    return total; 
} 
+0

を取得しますか? – AnhTriet

+1

'return MessageBox.Show' .....メソッドから返された' MessgeBox'を初めて見たことがあります。通常、メソッドはメッセージボックスを表示するか、呼び出しメソッドによってメッセージボックスに表示される値を返します。 – Tim

+0

ティム、それは間違いだった、私はそれを修正した。 – sam

答えて

3

これは簡単な方法です。

private void button1_Click(object sender, EventArgs e) 
{ 
    var wordCount = CountWords(textBox1.Text); 
    MessageBox.Show(wordCount.ToString()); 

} 
private int CountWords(string input) 
{ 
    var separators = new[] { ' ', '.' }; 
    var count = input.Split(separators, StringSplitOptions.RemoveEmptyEntries).Length; 
    return count; 
} 

追加/ separators配列から希望の区切りに/を削除します。

2

拡張メソッドを使用してください。それはいい考えです。

public static class MyExtentionClass 
{ 
    public static int WordCount(this string str) 
    { 
     var separators = new[] { ' ', '.', ',' }; 
     var count = str.Split(separators, StringSplitOptions.RemoveEmptyEntries).Length; 

     return count; 
    } 
} 


例:空白の

MessageBox.Show(textBox1.Text.WordCount()); 
0

スプリット、あなたのコードで何が悪いのカウント

int wordCount = textBox1.Text.Trim().Split(" ").Count; 
関連する問題