Console.Write("Enter word: ");
string word = Console.ReadLine();
var loc = word.IndexOfAny(new char[] { 'a', 'e', 'i', 'o', 'u' });
string word1 = loc >= 0 ? word.Insert(loc, "ub") : word;
Console.WriteLine(word1);
I get hubello
but I want hubellubo
instead.
CodePudding user response:
You're only doing a single modification to your string - whichever vowel you detect first. IndexOfAny
returns only the first match found.
Instead, you'll need to find all the vowels in your input string. You can do this with a loop, but it might be easier to do this with Regex replacments.
var input = "hello";
var pattern = "([aeiou])";
var replaced = Regex.Replace(input, pattern, "ub$1");
Console.WriteLine(replaced);
The capture group is needed to re-replace the found vowel back in the replacement.
CodePudding user response:
You need a loop to iterate each finding
string word = "hello";
char[] loc = new char[] { 'a', 'e', 'i', 'o', 'u' };
int minIndex = word.IndexOfAny(loc);
while (minIndex != -1)
{
string insert = "ub";
word = word.Insert(minIndex, insert);
minIndex = word.IndexOfAny(loc, minIndex insert.Length 1);
}
Console.WriteLine(word);
https://dotnetfiddle.net/kBPIrF
CodePudding user response:
Linq solution:
var input = "hello";
string replaced = string.Concat(input
.Select(c => "aeiou".Contains(c) ? $"ub{c}" : $"{c}"));
Console.WriteLine(replaced);
Here we scan each character c
within input
and either add "ub"
prefix or keep character as it was.