我做了一個需要.cs文件的小項目,讀取它們並返回文件中最頻繁的單詞。但是,現在它返回最常用的單詞是逗號。 我怎樣才能讓它分裂字符串忽略逗號?如何通過忽略逗號c#來拆分字符串?
例如:我有一個字符串:
,。 ? AA,B CDEF cfed,ABEF ABEF ABEF,
現在它返回一個最常見的詞是「ABEF」,它發生2次(程序不計第三ABEF,一個是與到底逗號)
又如:
,。 ? AA,B CDEF cfed,ABEF ABEF ABEF,,,
這個現在返回最常見的詞是一個逗號「」和它發生3次,但事情是 - 我希望我的程序忽略逗號並僅僅關注單詞。
namespace WindowsFormsApp8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text Documents |*.cs;*.txt", ValidateNames = true, Multiselect = false }) //openfiledialog (all .cs; all.txt)
{
if (ofd.ShowDialog() == DialogResult.OK) //if in file dialog a file gets selected
{
using (StreamReader sr = new StreamReader(ofd.FileName)) //text reader
{
richTextBox1.Text = await sr.ReadToEndAsync(); //reads the file and returns it into textbox
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
string[] userText = richTextBox1.Text.ToLower().Split(' ');
var frequencies = new Dictionary<string, int>(); // variable frequencies, dictionary with key string, value int.
string highestWord = null; //declare string highestword with starting value null.
int highestFreq = 0; //declare integer highestfreq with starting value zero.
foreach (string word in userText) //search words in our array userText that we declared at the beginning.
{
int freq; //declare integer freq.
frequencies.TryGetValue(word, out freq); //trygetvalue from dictionary key, out value.
freq += 1; //count it.
if (freq > highestFreq)
{
highestFreq = freq;
highestWord = word;
}
frequencies[word] = freq; //assign most frequent word in frequencies dictionary to freq
}
MessageBox.Show("the most occuring word is: " + highestWord + ", it occured " + highestFreq + " times"); //display data to messagebox.
}
}
}
向我們顯示您的代碼。取決於你如何做,這可能是1行代碼或5. – Amy
對不起,代碼現在被添加 –
僅供參考,評論如「//聲明字符串的最高字的起始值爲null」。不要提供任何價值。從它旁邊的代碼可以看出,您聲明瞭一個具有空值的變量。這樣的評論只是混亂。 – Amy