.net 如何查找字符串中所有单词的出现次数
标题说明了一切,我如何知道一个单词在一个字符串中出现了多少次。我不知道用户将输入什么,所以我不能用case测试它,有人能帮忙吗 我也可以只提取重要的单词吗 例如字符串.net 如何查找字符串中所有单词的出现次数,.net,vb.net,string,string-parsing,.net,Vb.net,String,String Parsing,标题说明了一切,我如何知道一个单词在一个字符串中出现了多少次。我不知道用户将输入什么,所以我不能用case测试它,有人能帮忙吗 我也可以只提取重要的单词吗 例如字符串“testing apples testing” 它应该告诉我,“testing”出现了2次,“apples”1次,然后返回一个带有{“testing”,“apples”} 可以通过将字符串拆分为空白字符来完成此操作 计算foreach块中的单词数 获取此代码的帮助 private void countWordsInString(s
“testing apples testing”
它应该告诉我,“testing”
出现了2次,“apples”
1次,然后返回一个带有{“testing”,“apples”}
private void countWordsInString(string yourString, Dictionary<string, int> words)
{
var text = yourString.ToString();
var allwords = Regex.Split(text, @"\W");
foreach (Match match in allwords.Matches(text))
{
int currentCount=0;
words.TryGetValue(match.Value, out currentCount);
currentCount++;
words[match.Value] = currentCount;
}
}
var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);
countWordsInString("testing apples testing", words);
private void countwords字符串(字符串yourString,字典单词)
{
var text=yourString.ToString();
var allwords=Regex.Split(文本@“\W”);
foreach(匹配allwords.Matches(文本))
{
int currentCount=0;
words.TryGetValue(match.Value,out currentCount);
currentCount++;
字[match.Value]=当前计数;
}
}
var words=新字典(StringComparer.CurrentCultureInoRecase);
countWordsInString(“测试苹果”,单词);
words[“apple”]返回字符串中“apple”的次数。这里有一个简单的oop方法:
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim testString As String = "testing apples testing dog cat dog apples testing cat dog log frog log"
Dim occurrences As List(Of ItemOccurrence) = GetOccurrence(testString)
For Each iO As ItemOccurrence In occurrences
MsgBox(iO.ToString)
Next
End Sub
Public Function GetOccurrence(source As String) As List(Of ItemOccurrence)
Dim parts As List(Of String) = source.Split({" "c}, StringSplitOptions.RemoveEmptyEntries).ToList
Dim results As New List(Of ItemOccurrence)
For Each Str As String In parts
Dim match As ItemOccurrence = Nothing
For i As Integer = 0 To results.Count - 1
If results(i).Text.ToLower = Str.ToLower Then match = results(i)
Next
If match Is Nothing Then
results.Add(New ItemOccurrence(Str))
Else
match.Count += 1
End If
Next
Return results
End Function
Public Class ItemOccurrence
Public Property Text As String = String.Empty
Public Property Count As Integer = 1
Sub New(text As String)
Me.Text = text
End Sub
Public Shadows Function ToString() As String
If Me.Count = 1 Then Return String.Format("""{0}"" occured {1} time in the string.", Text, Count)
Return String.Format("""{0}"" occured {1} times in the string.", Text, Count)
End Function
End Class
End Class
无论你尝试了什么,都可以发布你的代码。拆分字符串,然后应用分组,并获得每个单词的计数。对于重要的,你需要创建重要单词的字典,并对这些单词进行比较