简体   繁体   English

如何将其变成for循环?

[英]How do i turn this into a for loop?

Hey im wondering how to turn this into a for loop, so I don't have to copy this 26 times for each letter of the alphabet: 嘿,我想知道如何将其转换为for循环,所以我不必为字母表中的每个字母复制26次:

count[1] = str.Split('A').Length - 1;
Console.WriteLine("A comes up x " + count[1]);

count is a blank integer array that takes 26 values, that represent the amount of times a letter of the alphabet is in string str, stored in a string array called letters count是一个空白的整数数组,该数组具有26个值,表示字母在字符串str中的出现次数,存储在称为字母的字符串数组中

Instead of splitting and creating a new array, I would use the Count() function. 与其拆分和创建一个新数组,不如使用Count()函数。 You can then loop through each character, or loop your existing array. 然后,您可以循环浏览每个字符,或循环您现有的数组。

for (char c = 'A'; c <= 'Z'; c++)
{
    Console.WriteLine(c + " comes up x " + str.Count(x => char.ToUpper(x) == c));
}

here's one: 这是一个:

static void Main(string[] args)
{
    var letters = "abcdefghijklmnopqrstuvwxyz";
    var str = "the quick brown fox jumps over the lazy dog";

    for (int i = 0; i < letters.Length; i++)
        Console.WriteLine("{0} comes up {1} time(s)", letters[i], str.ToLower().Split(letters[i]).Length - 1);

    Console.Read();

}

You can use array to store the count for each character. 您可以使用数组存储每个字符的计数。 Split will be an expensive operation 拆分将是一项昂贵的操作

var str = "THISISJUSTATEST";
var array = new int[26];
foreach(var character in str.ToCharArray()){
if (character >= 'A' && character <= 'Z'){
  var index = character - 'A';
  array[index]++;
  }
}
for (int i = 0; i < 26; i++) {
  var c = i +'A';
  Console.WriteLine("{0} comes {1} time(s)", (char)c, array[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM