Search code examples
c#stringdifference

C#: Find Unknown Character in a String


I have * strings and I want the only unknown character and its position. For instance, I want character 'a' or 'b' or 'c' or anything (unknown) and its positions in the strings below:

1) "******a***" // I want 'a'
2) "b****"      // I want 'b'
3) "*******c"   // I want 'c'

The strings are always have * characters. Sometimes I have 'a', sometimes 'n', sometimes 'x', and so on. I don't know what character coming inside stars (*).

How can I do this in C#?


Solution

  • Try this:

    // the string
    var str = "******a***";
    
    // the character
    var chr = str.Single(x => x != '*');
    
    // the position
    var pos = str.IndexOf(chr);
    

    Please be aware that Single will throw an exception in case nothing found. Use it only when you're certain there's one (and only one) unknown character. If you're not sure use SingleOrDefault and check for Char.MinValue.