-1

I want to check on how many times does k appears. this is what i have done so far and am not getting the results.

class Program
{
    static void Main(string[] args)
    {
        int count = 0;
        string str = "hnfdjkkedjjykukyukrtrnrkkkkt";
        string l;

        for (int i = 0; i < str.Length; i++)
        {
            l = str.Substring(1, 1);
            if (l == "k")
            {
                count++;
            }
        }
        Console.WriteLine("k appears " + count++ + " times");
        Console.ReadKey();
    }
}
uTeisT
  • 2,256
  • 14
  • 26

3 Answers3

3

You can try :

int count = str.Count(c => c=='k')

Hope this help :-)

Arcord
  • 1,724
  • 1
  • 11
  • 16
2

You can go as simple as

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string s = "aasfkkfasfas";
        int count = s.Count(l => l== 'k');

        Console.WriteLine(count);
    }
}

Calling Substring for each letter is really not the best solution. Keep in mind that string implements IEnumerable so you can also do it like this:

using System;

public class Program
{
    public static void Main()
    {
        string s = "aasfkkfasfas";
        int count = 0;
        foreach(char c in s)
        {
            if(c == 'k') 
                count++;
        }

        Console.WriteLine(count);
    }
}

This is closer to your original solution.

Shocked
  • 627
  • 4
  • 13
0

You can also use RegEx (Regular Expressions) for that but it's kind of overkill for your use case.

It's found in the namespace System.Text.RegularExpressions (see MSDN).

Regex.Matches(text, pattern).Count

In your case, it would be

Regex.Matches("hnfdjkkedjjykukyukrtrnrkkkkt", "[k]").Count
jAC
  • 5,195
  • 6
  • 40
  • 55