How to count all instances of a specific character in a string with C#

2 Answers

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        public int Length { get; private set; }

        static void Main(string[] args)
        {
            const string s = "java c# c++ ada";

            int i = 0, count = 0;
            while ((i = s.IndexOf('a', i)) != -1)
            {
                count++;

                i++;
            }
            Console.WriteLine(count);
        }
    }
}


/*
run:
     
4

*/

 



answered Dec 25, 2016 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        public int Length { get; private set; }

        static void Main(string[] args)
        {
            const string s = "java c# c++ ada";

            int i = 0, count = 0;
            char ch = 'a';
            while ((i = s.IndexOf(ch, i)) != -1)
            {
                count++;

                i++;
            }
            Console.WriteLine(count);
        }
    }
}


/*
run:
     
4

*/

 



answered Dec 25, 2016 by avibootz
...