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:
Enumerable.Select
to map over the characters and indices and convert them to (character, index)
tuples.Enumerable.GroupBy
to group tuples by character.Enumerable.ToDictionary
, which maps each character to an IEnumerable<int>
of indices.Dictionary<TKey,TValue>.TryGetValue(TKey, TValue)
to get the associated indices for the letter.
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.