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
}
}
}
}
}
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;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With