w3resource

C# Sharp Exercises: Check if a string has all unique characters

C# Sharp String: Exercise-68 with Solution

Write a C# Sharp program to check whether all the characters in a given string are unique or not. If all the characters are unique return "There is no similarity between any of the characters!" otherwise if not unique, then:

  • Display a message stating this.
  • Display the duplicated character.
  • It is only necessary to display the first non-unique character.
  • Display where "both" duplicated characters appears in the string.
  • All of the above messages can be incorporated into a single message.

Sample Solution:

C# Sharp Code:

using System;
using System.Linq;

namespace exercises
{
    class Program
    {
        static void Main(string[] args)

        {
            string[] text = { "", ".", "cppCPP", "PQR RQP", "The quick brown fox jumps over the lazy dog.", "C Sharp" };
            foreach (string word in text)
            {
                Console.WriteLine($"\n\"{word}\" (Length {word.Length}) " +
                    string.Join(", ",
                        word.Select((ch, i) => (ch, i))
                        .GroupBy(tm => tm.ch).Where(gr => gr.Count() > 1)
                        .Select(gr => $"'{gr.Key}'[{string.Join(", ", gr.Select(tm => tm.i))}]")
                        .DefaultIfEmpty("There is no similarity between any of the characters!")));
            }
        }
    }
}

Sample Output:

"" (Length 0) There is no similarity between any of the characters!
"." (Length 1) There is no similarity between any of the characters!
"cppCPP" (Length 6) 'p'[1, 2], 'P'[4, 5]
"PQR RQP" (Length 7) 'P'[0, 6], 'Q'[1, 5], 'R'[2, 4]
"The quick brown fox jumps over the lazy dog." (Length 44) 'h'[1, 32], 'e'[2, 28, 33], ' '[3, 9, 15, 19, 25, 30, 34, 39], 'u'[5, 21], 'r'[11, 29], 'o'[12, 17, 26, 41]
"C Sharp" (Length 7) There is no similarity between any of the characters!

Flowchart :

Flowchart: C# Sharp Exercises - Check if a string has all unique characters.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous C# Sharp Exercise: Convert ASCII text to hexadecimal value as a string.
Next C# Sharp Exercise: C# Sharp programming exercises Function with Solution.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter