簡體   English   中英

在 C# 中,如何在文本中搜索數組中的單詞並將其存儲在第二個數組中

[英]In C# how to search a text for words in a array and store in a second array

我需要在文本中搜索數組中的單詞並有效地保存到第二個數組。

Example:
string[] myWords = {"Java","CSharp","OO", "and", "mvc"};
string Text = "Both CSharp and Java have mvc frameworks and are OO languages."

Result in Second Array:
  {  "CSharp", "and" , "Java", "mvc", "and", "OO" }

帶計數的獨特單詞也可以。

任何幫助,將不勝感激。

不確定這是否有效,但在我的腦海中:

        List<string> newCollection = new List<string>();
        string[] myWords = { "Java", "CSharp", "OO", "and", "mvc" };
        string Text = "Both CSharp and Java have mvc frameworks and are OO languages.";
        string[] splitText = Text.Split(' ');
        foreach(string s in splitText)
        {
            if (myWords.Contains(s))
                newCollection.Add(s);
        }

或者在 myWords 數組中拆分

            List<string> x = new List<string>();
            List<string> newCollection = new List<string>();
            string[] myWords = { "Java have", "CSharp", "OO", "and", "mvc" };

            string Text = "Both CSharp and Java have mvc frameworks and are OO languages.";
            string[] splitText = Text.Split(' ');

            foreach (string s2 in myWords)
            {
                string[] b = s2.Split(' ');
                foreach(string c in b)
                {
                    x.Add(c);
                }
            }

            foreach (string d in splitText)
            {
                if (x.Contains(d))
                {
                    newCollection.Add(d);
                    Console.WriteLine(d);
                }

            }

這是一個更簡潔的版本:

List<string> newCollection = new List<string>();
string[] myWords = { "Java have", "CSharp", "OO", "and", "mvc" };

string Text = "Both CSharp and Java have mvc frameworks and are OO languages.";

string[] splitText = Text.Split(' ');

List<string> x = SplitArray(myWords);

foreach (string d in splitText)
{
    if (x.Contains(d))
    {
        newCollection.Add(d);
        Console.WriteLine(d);
    }

}

拆分數組的函數

public static List<string> SplitArray(string[] strArray)
{
    List<string> rtnArray = new List<string>();
    foreach (string a in strArray)
    {
        string[] x = a.Split(' ');
        foreach(string b in x)
            rtnArray.Add(b);
    }
    return rtnArray;
}

您可以使用字典來跟蹤每個單詞的實例數。 例如

Dictionary<string, int> wordDict = new Dictionary<string, int> {
    { "Java", 0 },
    { "CSharp", 0 },
    { "OO", 0 },
    { "and", 0 },
    { "mvc", 0 }
};

string text = "Both CSharp and Java have mvc frameworks and are OO languages."
string[] split = text.Split(' ');
foreach(string s in split)
{
    if (wordDict.ContainsKey(s)) {
        wordDict[s] = wordDict[s] + 1;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM