做
private letterCount a = null;
out of your methods,and
a = new letterCount(0);
這裏面的方法實際上是。 只要小心,如果第二個方法在第一個方法之前被調用,就會得到一個錯誤(因爲沒有實例化)。爲了避免這種情況(除非有特殊原因的實例化它,只有當第一個方法被調用),你可以做
private letterCount a = new letterCount(0);
直接,出了這兩種方法。
編輯:
那好吧意見後,我建議了不同的方法,像這樣:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
var a = letterCounter("The quick brown fox jumps over the lazy dog");
Console.ReadKey();
}
private const string charsToBeCounted = "abcdefghikjlmnopqrstuvwxyz"; // ABCDEFGHIKJLMNOPQRSTUVWXYZ capital letters not needed converting the string to lowercase
public static Dictionary<char, int> letterCounter(string word)
{
var ret = new Dictionary<char, int>();
word = word.ToLower();
foreach (char ch in word)
{
if (charsToBeCounted.Contains(ch))
{
if (ret.ContainsKey(ch))
ret[ch]++;
else
ret[ch] = 1;
}
}
return ret;
}
}
}
該函數返回一個字典,其中的字母鍵和計數器是值。不需要所有這些對象。
EDIT2:
要使用結果這樣做:
private void button1_Click(object sender, EventArgs e)
{
var d = letterCounter(textBox1.Text);
textBox2.Text = string.Empty;
foreach(char c in d.Keys)
{
textBox2.Text += d[c].ToString() + " ";
}
}
EDIT3:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
var a = letterCounter("The quick brown fox jumps over the lazy dog");
Console.ReadKey();
}
public class letter
{
public int count;
public string stringValue;
}
private const string charsToBeCounted = "abcdefghikjlmnopqrstuvwxyz"; // ABCDEFGHIKJLMNOPQRSTUVWXYZ capital letters not needed converting the string to lowercase
public static Dictionary<char, letter> letterCounter(string word)
{
var ret = new Dictionary<char, letter>();
word = word.ToLower();
foreach (char ch in word)
{
if (charsToBeCounted.Contains(ch))
{
letter l = null;
if (ret.ContainsKey(ch))
l = ret[ch];
else
{
l = new letter();
ret.Add(ch, l);
}
l.count++;
l.stringValue = "Any value you want";
}
}
return ret;
}
}
}
那麼你的按鈕將變爲:
private void button1_Click(object sender, EventArgs e)
{
var d = letterCounter(textBox1.Text);
textBox2.Text = string.Empty;
foreach(char c in d.Keys)
{
textBox2.Text += d[c].count.ToString() + " ";
}
}
我想你不理解我 - 我會張貼你的照片http://imgur.com/22pIM7U – urgot
@urgot請發佈完整的代碼,然後。其實代碼本身的目的不明確。 –
http://pastebin.com/jpqdJMdZ 程序應該這樣做:計算輸入字符串中字母的出現次數,但是我也需要每次按下按鈕時重置計數器 – urgot