How to find the first non-repeated character in a string with C#

3 Answers

0 votes
using System;
  
class NonRepeatedCharacter
{
   static char getFirstNonRepeatedCharacter(string s) { 
        int[] count = new int[256];
        int length = s.Length;
    
        for (int i = 0; i < length; i++) 
            if (s[i] != ' ') 
                count[(int)s[i]]++; 
 
        for (int i = 0; i < length; i++) 
            if (count[(int)s[i]] == 1) 
               return s[i];
                   
        return ' ';
    } 
    static void Main()
    {
        string s = "csharp programming"; 
            
        char ch = getFirstNonRepeatedCharacter(s); 
        
        Console.WriteLine(ch);
    }
}
  
  
/*
run:
    
c
    
*/

 



answered Feb 9, 2019 by avibootz
edited Jan 4, 2025 by avibootz
0 votes
using System;
 
class NonRepeatedCharacter
{
    public static char GetFirstNonRepeatedCharacter(string str) {  
        int[] occurrences = new int[256]; 
        int length = str.Length;
        
        for (int i = 0; i < length; i++) {  
            occurrences[str[i]]++;  
        }  
         
        for (int i = 0; i < length; i++) {   
            if (occurrences[str[i]] == 1) {  
                return str[i];  
            }  
        }  
        
        return ' ';  
    }  
    static void Main() {
        string str = "csharp programming";
 
        Console.Write(GetFirstNonRepeatedCharacter(str));
    }
}

 
 
/*
run:
 
c
 
*/

 



answered Jan 4, 2025 by avibootz
0 votes
using System;
using System.Collections.Generic;

class NonRepeatedCharacter
{
    static void Main()
    {
        string str = "ppdadxefe";
        
        char? result = FindFirstNonRepeatedChar(str);
        
        Console.WriteLine(result.HasValue ? $"First non-repeated character: {result}" : "No non-repeated character found.");
    }

    static char? FindFirstNonRepeatedChar(string str) {
        var charCount = new Dictionary<char, int>();

        foreach (char ch in str) {
            if (charCount.ContainsKey(ch))
                charCount[ch]++;
            else
                charCount[ch] = 1;
        }

        foreach (char ch in str) {
            if (charCount[ch] == 1)
                return ch;
        }

        return null;
    }
}



/*
run:

First non-repeated character: a

*/

 



answered Jun 28, 2025 by avibootz
edited Jun 28, 2025 by avibootz
...