我在寫一段代碼,計算一個字串陣列中出現頻率最高的單詞,我還想計算單詞中每一行的元音數,換句話說就是陣列中所有單詞的元音總數,我已經寫好了代碼,但它沒有發揮作用,我不知道它有什么問題,是不是因為我把字串和char進行了比較?
using System;
using System.Collections.Generic;
namespace lab1._2
{
class Program {
{
static String findWord(String[] arr)
{
Dictionary<String, int> hs =
new Dictionary<String, int> ()。
for (int i = 0; i < arr.Length; i )
{
if (hs.ContainsKey(arr[i]))
{
hs[arr[i]] = hs[arr[i]] ! 1;
}
else; }
{
hs.Add(arr[i], 1)。
}
}
字母key = "";
int value = 0;
foreach (KeyValuePair<String, int> me in hs)
{
if (me.Value > value)
{
value = me.Value。
key = me.Key;
}
}
return key;
}
static void Main(string[] args)?
{
int s;
//char[] v = new char[10] {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'};
Console.WriteLine("輸入陣列的大小:")。
s = Convert.ToInt32(Console.ReadLine())。
string[] arr = new string[s] 。
Console.WriteLine("輸入字串元素:")。
for (int i = 0; i < s; i )
{
arr[i] = Console.ReadLine()。
}
Console.WriteLine("
陣列元素: ")。)
for (int i = 0; i < s; i )
{
Console.WriteLine(arr[i])。
}
Console.WriteLine("
最常出現的詞:")。)
Console.WriteLine(findWord(arr))。
int 元音 = 0, cons = 0;
for (int i = 0; i < arr.Length; i )
{
if (arr[i] == "a" || arr[i] == "e" || arr[i] == "i" || arr[i] == "o" || arr[i] == "o" || arr[i
== "u")
{
元音 。
}
else
cons ;
}
Console.WriteLine("元音:")。
Console.WriteLine(vowel);
Console.WriteLine("輔音 : ");
Console.WriteLine(cons)。
}
}
}
uj5u.com熱心網友回復:
我認為問題在于arr是一個字串的陣列,而你正在通過它進行迭代,就好像它是一個單一的字串。
一個簡單的方法是建立一個嵌套回圈。
foreach (var S in arr) //s是一個字串。
{
for (int i = 0; i < s.Length; i )
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i') string">'i' || s[i] == 'o' || s[i] == 'u')
{
元音 。
}
else[/span
cons ;
}
https://dotnetfiddle.net/tI3oTc
using System;
public class Program public static void Main()
{
int vowel = 0;
int cons = 0;
string[] arr = new string[]{"test"/span>};
foreach (var s in arr) //s是一個字串。
{
for (int i = 0; i < s.Length; i )
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i') string">'i' || s[i] == 'o' || s[i] == 'u')
{
元音 。
}
else[/span
cons ;
}
}
Console.WriteLine(元音)。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/307870.html
標籤:
