w3resource

C# Sharp Exercises: String with same characters

C# Sharp Basic: Exercise-96 with Solution

Write a C# Sharp program to check whether all the characters in a string are the same. Return true if all the characters in the said string are same otherwise false.

Sample Data:
("aaa") -> True
("abcd") -> False
("3333") -> True
("2342342") -> False

Sample Solution:

C# Sharp Code:

using System;
namespace exercises
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "aaa";
            Console.WriteLine("Original string: " + text);
            Console.WriteLine("Check whether all the characters in the said string are same or not! " + test(text));
            text = "abcd";
            Console.WriteLine("Original string: " + text);
            Console.WriteLine("Check whether all the characters in the said string are same or not! " + test(text));
            text = "3333";
            Console.WriteLine("Original string: " + text);
            Console.WriteLine("Check whether all the characters in the said string are same or not! " + test(text));
            text = "2342342";
            Console.WriteLine("Original string: " + text);
            Console.WriteLine("Check whether all the characters in the said string are same or not! " + test(text));
        }
        public static bool test(string text)
        {
            if (text.Length > 1)
            {
                var b = text[0];
                for (int i = 1; i < text.Length; i++)
                {
                    var c = text[i];
                    if (c != b)
                    {
                        return false;
                    }

                }

            }
            return true;
        }
    }
}

Sample Output:

Original string: aaa
Check whether all the characters in the said string are same or not! True
Original string: abcd
Check whether all the characters in the said string are same or not! False
Original string: 3333
Check whether all the characters in the said string are same or not! True
Original string: 2342342
Check whether all the characters in the said string are same or not! False

Flowchart:

Flowchart: C# Sharp Exercises - String with same characters.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous C# Sharp Exercise: Verify that a string contains valid parentheses.
Next C# Sharp Exercise: Check if a string is numeric or not.

What is the difficulty level of this exercise?



Share this Tutorial / Exercise on : Facebook and Twitter