find position of a character in a string in C Sharp

find position of a character in a string in C# – Learn how to find the position of a character with example programs.

Input string : viswanath
position of input character – s is 3

Method-1

C# program to find the index of a string using for loop

C# code

using System;
class FindPosition
    {
        static void Main(string[] args)
        {    //// Enter user defined String input
            Console.WriteLine("Enter String : ");
            string str = Console.ReadLine();

            // Enter the char which you want to
            // search for its position.
            Console.WriteLine("Enter the character:");
            ConsoleKeyInfo ch = Console.ReadKey();


            int indexPosition = -1;

            // Count the index position of char in string.

            for (int i = 0; i < str.Length; i++)
            {
                if (str[i]==ch.KeyChar)
                {
                    indexPosition = i;
                    break;
                }
            }

            if(indexPosition ==-1 )
            {
                Console.WriteLine("character, {0} is not found in string",ch.KeyChar);
            }
            else
            {
                Console.WriteLine("character, {0} is  found in string at {1} position",ch.KeyChar,indexPosition+1);
            }
        }
    }

Output

Enter String :
viswanath
Enter the character:
w
character, w is found in string at 4 position

Method-2

C# program to find the index of a string using string handling function.

C# code

using System;
class FindPosition
    {
        static void Main(string[] args)
        {    // Enter user defined String input
            Console.WriteLine("Enter String : ");
            string str = Console.ReadLine();

            // Enter the char which you want to
            // search for its position.
            Console.WriteLine("Enter the character:");
            ConsoleKeyInfo  ch= Console.ReadKey();


            int indexPosition = -1;

            // Count the index position of char in string.

            indexPosition = str.IndexOf(ch.KeyChar);

            

            if(indexPosition ==-1 )
            {
                Console.WriteLine("\n character, {0} is not found in string",ch.KeyChar);
            }
            else
            {
                Console.WriteLine("\n character, {0} is  found in string at {1} position",ch.KeyChar,indexPosition+1);
            }
        }
    }

Output

Enter String :
viswanath
Enter the character:
k
character, k is not found in string