Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding array element within a string C#

I've been looking for a way to check a string for elements of an array and if it contains one of those elements to return the indexOf it but i'm having trouble finding a way to do this. Most of my searches end up showing me way to find the indexOf an element in an array or something similar.

As a bit of background I'm trying to create a program that takes a string from user input, splits the words of the paragraph into an array, performs certain checks on them and changes them accordingly.

For instance if the current word starts with a consonant it finds the first vowel and moves all the letters in front of it to the end of the word. This is what I tried but it prints an index of 14 so clearly something is wrong:

char[] vowelsList = new char[] { 'A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u' };

foreach (char vowel in vowelsList)
{
    if (currentWord.Contains(vowel))
    {
        int index = currentWord.IndexOf(vowel);
        System.Diagnostics.Debug.Write(index);
    }
}

currentWord is the word from the string from the user input that is currently being checked.

Any suggestion on different methods or keywords to try is appreciated.

EDIT

I apologise the code is actually fine, it was returning 1 and 4 because it was always receiving the input Hello and i was misinterpreting what was going on, I'm a bit of an idiot sometimes. I guess then my question would be how to get this code to only find the index of the first vowel but a poster has already stated how to do that, thank you all for the help and suggestions, most of which I have implemented.

like image 520
fost Avatar asked Apr 27 '26 16:04

fost


1 Answers

You probably want to use String.IndexOfAny, which returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.

If no character is found, it returns -1.

var index = currentWord.IndexOfAny(vowelsList);
if (index >= 0)
{ 
    // do stuff
}

Note that, as stated on MSDN, this method performs an ordinal (culture-insensitive) search, where a character is considered equivalent to another character only if their Unicode scalar value are the same. To perform a culture-sensitive search, you would need to use an overload of CompareInfo.IndexOf method, where a Unicode scalar value representing a precomposed character.

like image 68
Groo Avatar answered Apr 30 '26 06:04

Groo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!