How to check if a string contains only unique characters in C#

2 Answers

0 votes
using System;
 
class Program
{
    static bool contains_unique_chars(string s) { 
        char[] arr = s.ToCharArray(); 
   
        Array.Sort(arr); 
   
        for (int i = 0; i < arr.Length - 1; i++) { 
            if (arr[i] == arr[i + 1]) 
                return false; 
        } 
   
        return true; 
    } 
    static void Main() {
        string s = "abcde"; 
    
        if (contains_unique_chars(s)) { 
            Console.Write("yes");
        } 
        else { 
            Console.Write("no");
        } 
    }
}
 
 
 
 
/*
run:
 
yes
 
*/

 



answered Dec 29, 2019 by avibootz
edited Dec 29, 2019 by avibootz
0 votes
using System;
using System.Linq;
  
class Program
{
    static bool contains_unique_chars(string s) { 
        s = String.Concat(s.OrderBy(ch => ch));

        for (int i = 0; i < s.Length - 1; i++) { 
            if (s[i] == s[i + 1]) 
                return false; 
        } 
    
        return true; 
    } 
    static void Main() {
        string s = "abcde"; 
     
        if (contains_unique_chars(s)) { 
            Console.Write("yes");
        } 
        else { 
            Console.Write("no");
        } 
    }
}
  


/*
run:
  
yes
  
*/

 



answered Dec 30, 2019 by avibootz

Related questions

1 answer 176 views
2 answers 281 views
1 answer 169 views
2 answers 277 views
1 answer 170 views
4 answers 288 views
...