-5

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.

mxy
  • 1
  • 1
  • 2
  • 1
    Your choice of tags would seem to indicate you already know one answer: **loop** thru the **chars** in the **string** to see if it matches the **letter** entered. – Ňɏssa Pøngjǣrdenlarp Nov 23 '19 at 23:02
  • Possible duplicate of [Finding all positions of substring in a larger string in C#](https://stackoverflow.com/questions/2641326/finding-all-positions-of-substring-in-a-larger-string-in-c-sharp) – devNull Nov 23 '19 at 23:07
  • Thank you. I have tried it so many times on my own using loops but I just was not able to get the correct result. That's why I am here. – mxy Nov 23 '19 at 23:17
  • 1
    Next time, if you post the code you have tried and are working with, you are much less likely to collect downvotes. As posted this is asking 'how to write a program' which is too broad. Visit the [help] and study some of the topic there like [ask] – Ňɏssa Pøngjǣrdenlarp Nov 23 '19 at 23:30
  • Well, for me votes are not that important. I am satisfied with the most simple answers. Like "You can use IndexOf" or soemthing like that. If people are kind enough to show me the actual code, that is a bonus for me. My code was not even something you could really work with. The whole char-searching part was missing because I did not know what to add and the rest was just a loop. Thx. – mxy Nov 24 '19 at 12:09

2 Answers2

4

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);
}
José Pedro
  • 1,097
  • 3
  • 14
  • 24
0

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:

RoadRunner
  • 25,803
  • 6
  • 42
  • 75