Solved

C# Algorithm: Given a string, find the first non-repeating character in it

Posted on 2013-12-12
3
618 Views
Last Modified: 2013-12-12
Can any one help with this please?
0
Comment
Question by:Techsavy
  • 2
3 Comments
 
LVL 8

Accepted Solution

by:
virtuadept earned 500 total points
ID: 39714881
This solution was found here:
stackoverflow.com/questions/3994644/c-sharp-logic-to-get-the-first-non-repeatingdistinct-character-from-the-string

LINQ version:

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

Open in new window


Non LINQ version:

 
  for (int index = 0; index < str.Length; index++)
    {
        if (str.LastIndexOf(str[index]) == str.IndexOf(str[index]))
        {
            result = str[index];
            break;
        }
    }

Open in new window

0
 

Author Closing Comment

by:Techsavy
ID: 39714929
Very Easy to Follow
0
 
LVL 8

Expert Comment

by:virtuadept
ID: 39715002
I like the one-liner LINQ solution if you have a recent C#.NET, but for older versions of C# you may need to use the looping solution. Enjoy!
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question