Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic to get the first non-repeating(distinct) character from the string

Tags:

c#

In c# i want to create logic that if i a string like abcabda is passed to a method then it should return first non repeative character from string like in above it should return c. i am unable to convert a string to array of character then how to make comparison of each array character to the string and return the first non repeative character.

CanI make it like this?

class A
{
    static void main()
    {
        A a=new A();
        char  ch=a.m1(abcabd);
    }
}

class B
{
    char m1(string s)
    {
        string s1=s;
        char[] ch1=new char[s.length];
        for(int x=0; x<s.length;x++)
        {
            ch1[x]=s[x];
        }
        for(int x=0; x<s.length; x++)
        {
            for(int y=0; y<s.lenth; y++)
            {
                if(s[x]=ch1[y])
                {             
/// here i am confused how to create logic for comparison please let me know
// and how to return the character
                }
            }
        }
    }
}
like image 944
NoviceToDotNet Avatar asked Oct 22 '10 07:10

NoviceToDotNet


2 Answers

It seems that you are looking for the first char in the string with its count equals to 1?

using System.Linq;
string str = "abcabda";
char result = str.FirstOrDefault(ch => str.IndexOf(ch) == str.LastIndexOf(ch));

Non LINQ version:

    for (int index = 0; index < str.Length; index++)
    {
        if (str.LastIndexOf(str[index]) == str.IndexOf(str[index]))
        {
            result = str[index];
            break;
        }
    }
like image 132
Cheng Chen Avatar answered Oct 11 '22 22:10

Cheng Chen


You could use a bit of LINQ:

char result = input
    .GroupBy(c => c)             // group the characters
    .Where(g => g.Count() == 1)  // filter out groups with only 1 occurence
    .Select(g => g.Key)          // get the character from each remaining group
    .First();                    // return the first one
like image 25
Fredrik Mörk Avatar answered Oct 11 '22 22:10

Fredrik Mörk