Find the first non-repeated character in a string using C#

I am working to solve this problem. I have to find the first nonrepeated character in a string.

For example, Input : “teeter” Output: r

I am going to first use HashTables :

class Program
{
    static void Main()
    {
        var inputString =  “teeter” ;
        Hashtable hashtable = new Hashtable();
        int numb = 1; 
        for (int i=0; i< inputString.length(); i++)
        {   
             if (!hashtable.ContainsKey(hashtable[i])) 
                 hashtable.Add(hashtable[i], numb);
             else  
                 hashtable[hashtable[i]] = hashtable[i].Value+ 1 ;
        }
    }
}

Can I solve this problem using LinQ:

numb = inputString.First(1 == inputString.Where(item => 
                              item == hashtable[i]).Count());

My questions are :

-I have to solve this problem using LINQ and using HashTables or Dictionaries. Does my solutions ture ?

Answers


I don't think you need HashTable at all. Because string implements IEnumerable<char> you can use LINQ directly on your input string:

var letter = input.GroupBy(x => x).First(g => g.Count() == 1).Key;

Getting back to your HashTable solution. You 're not using it correctly. HashTable is not the same as Dictionary. It does not have key/value, it just has keys. You're looking for Dictionary here:

var inputString =  "teeter";
var dict = new Dictionary<char, int>();
int numb = 1; 
for (int i=0; i< inputString.length(); i++)
{   
     if (!dict.ContainsKey(inputString[i])) 
         dict.Add(inputString[i], numb);
     else  
         dict[inputString[i]] += 1;
}

// throws an ArgumentNullException if s is null.
// throws an InvalidOperationException if there is no non repeating character.
char FirstNonRepeater(string s)
{
    return s.ToLookup(c => c).First(g => g.Count() == 1).Key;
}

For a solution without HashTables, Dictionaries or LINQ, just remove duplicate characters from the string:

while (s.IndexOf(s[0], 1) != -1) {
  s = s.Replace(s[0].ToString(), "");
}
char result = s[0];

Need Your Help

Android: bitmap size exceeds VM budget (frame by frame)

android animation frame android-animation out-of-memory

I get this error all the time. And as I can see, there are a lot of questions already on stackoverflow.com, but sadly, I don't find any answers which will suit me.

Joining of pages from same PDF Form results in un-saveable PDF in itextSharp

c# forms merge itextsharp

I have an application PDF form consisting of 2 pages. The second page should be used only if the first page does not have enough space. And if the second page does not, one should print then a new ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.