0

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:

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

  • hint: have an array with ['A', 'B',...] and loop over that or something like this http://stackoverflow.com/questions/289792/int-to-char-in-c-sharp – dbarnes Jun 20 '15 at 02:25
  • Thanks sorry i forgot to mention have a string array called letters, that has all those – Matt Brittain Jun 20 '15 at 02:30

3 Answers3

4

Instead of splitting and creating a new array, I would use the Count() function. 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));
}
Cyral
  • 13,999
  • 6
  • 50
  • 90
0

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();

}
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
0

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]);
}
Ankit Vijay
  • 3,752
  • 4
  • 30
  • 53