简体   繁体   中英

How can I find a certain letter in a String in C#?

How can I search a certain letter (char) in a String?

I have to code a little riddle. You basicalley have to guess the right letters of an unknown word. Only the first letter is shown.

Example: "Apple"

A____ --> that's what you actually see. Now, the player has to input a letter/char and if it is inculded in the String "Apple", the correct letter will be added.

Example: input = e A___e

Thx.

You can use String.IndexOf .

Example:

var str = "Apple";
var c = 'p';
var i = str.IndexOf(c);
// i will be the index of the first occurrence of 'p' in str, or -1 if not found.

if (i == -1)
{
    // not found
}
else
{
    do
    {
        // do something with index i, which is != -1
        i = str.IndexOf(c, i + 1);
    } while (i != -1);
}

If you want to find all letter indices, you can try this LINQ solution:

var str = "Apple";
var letter = 'p';

var charIndexMap = str
    .Select((ch, idx) => (ch, idx))
    .GroupBy(pair => pair.ch)
    .ToDictionary(entry => entry.Key, 
                  entry => entry.Select(pair => pair.idx));

if (charIndexMap.TryGetValue(letter, out var value))
{
    Console.WriteLine("[" + string.Join(", ", value) + "]");
} else
{
    // not found
}

Output:

[1, 2]

Explanation:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM