0

私はこれに問題があります。ユーザーは文字列を入力する必要があり、次に文字列を数えて同じ文字列を乗算する必要があります。たとえば、ユーザーが次の文字列を入力した場合、The quick Brown fox jumps over the lazy dog;
出力は次のようになります。The = 22% 速い = 11% 茶色 = 11% fox = 11% jumps = 11% over = 11% lazy = 11% dog = 11%

これが私のコードです

 string phrase = "The quick brown fox jumps over the lazy dog";
        string[] arr1 = phrase.Split(' ');


        for (int a = 0; a < arr1.Length; a++)
        {
            Console.WriteLine(arr1[a]);
        }



        Console.ReadKey();

値は 22% で、2/9 * 100 という式を使用して計算されました。「the」が 2 回使用されているため 2 を、文字列に 9 つの単語があるため 9 で割ります。各文字列を比較して、それらが同じであるかどうかを判断しようとしていますが、そうすることができません。

4

5 に答える 5

3

必須の LINQ バージョン:

string phrase = "The quick brown fox jumps over the lazy dog";
string[] words = phrase.Split(' ');
var wc = from word in words
         group word by word.ToLowerInvariant() into g
         select new {Word = g.Key, Freq = (float)g.Count() / words.Length * 100};
于 2013-02-17T03:17:09.577 に答える
1

LINQ!の最小限の使用

        string phrase = "The quick brown fox jumps over the lazy dog";
        string[] words = phrase.ToLower().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        var distinct_words = words.Distinct().ToArray();
        foreach (string word in distinct_words)
        {
            int count = words.Count(wrd => wrd == word);
            Console.WriteLine("{0} = {1} % ", word, count * 100 / words.Length);
        }

または

        string phrase = "The quick brown fox jumps over the lazy dog";
        string[] words = phrase.ToLower().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        var needed_lines =  from word in words.Distinct() let count = words.Count(wrd => wrd == word) select String.Format("{0} = {1} % ", word, count * 100 / words.Length);

        foreach (string neededLine in needed_lines)
        {
            Console.WriteLine(neededLine);
        }
于 2013-02-17T03:24:16.403 に答える
0

2つのリストを使用してこれを行います

List<String> words  = new List<String>();
List<int> weight = new List<int>();

文字列を調べて、一意の単語のみを単語リストに追加すると、重みリストの対応するインデックスが 1 増加します。

次に、完了したら、各重み値を文字列の長さで割ることができます[]

一意の値を取得するには、次のようにします。

  • リストに最初の文字列を自動的に追加
  • その後のすべての文字列に対して、words.Contains(string[x]) を実行します。
  • 含まれていない場合は追加します
  • 含まれている場合は、words.indexOf(string[x]) を実行します。
  • 次に、重みリストの対応するインデックスを増やします
于 2013-02-17T03:07:03.480 に答える
0
string phrase = "The quick brown fox jumps over the lazy dog";
var parts = phrase.Split(' ');
var wordRatios = parts
                    .GroupBy(w => w.ToLower())
                    .Select(g => new{
                        word = g.Key,
                        pct = Math.Round(g.Count() * 100d / parts.Length)
                    });
于 2013-02-17T03:20:34.297 に答える
0

これを試すことができます:

 var  yourarr = phrase.Split(' ').GroupBy(word => word.ToUpper()).Select(w => ((w.Count()*100/ phrase.Split(' ').Distinct().Count())).ToString()+"%");
于 2013-02-17T03:53:40.763 に答える