You can use Regex.Replace:
Regex r = new Regex("[aAeEiIoOuU]");
//or Regex r = new Regex("[aeiou]", RegexOptions.IgnoreCase);
string[] names = new string[5];
names[0] = "john";
names[1] = "samuel";
names[2] = "kevin";
names[3] = "steve";
names[4] = "martyn";
for (int i = 0; i < names.Length; i++)
{
names[i] = r.Replace(names[i], "");
Console.WriteLine("The output is:" + names[i]);
}
To make your original approach work you need to add a call to string.Replace:
names[i] = names[i].Replace(vowels[j], "");
That says "replace any occurances of vowels[j]
in names[i]
and assign the result to names[i]
".
However, you are currently declaring your array of names inside your vowel loop so you're not going to quite get the result you expect if you add the replacement code.
You're also looping around the vowels and then the names; logically it probably makes sense to reverse this - that certainly makes outputting the results easier. Something like this should work for you:
string[] vowels = new string[] { "A", "a", "E", "e", "I", "i", "O", "o", "U", "u" };
string[] names = new string[5];
names[0] = "john";
names[1] = "samuel";
names[2] = "kevin";
names[3] = "steve";
names[4] = "martyn";
for (int i = 0; i < names.Length; i++)
{
for (int j = 0; j < vowels.Length; j++)
{
names[i] = names[i].Replace(vowels[j], "");
}
Console.WriteLine("The output is:" + names[i]);
}
Edit
In the comments the OP asked for an example without using Replace
. Here is one such method (@Eser has another in their answer). This approach iterates each character of the input string until it finds a vowel. At that point the characters that have been read up until then (excluding the vowel) are added to a StringBuilder
:
public static string RemoveVowels(string name)
{
StringBuilder noVowels = new StringBuilder();
//keep track of the last index we read
int lastIndex = 0;
int i;
for (i = 0; i < name.Length; i++)
{
if (vowels.Contains(name[i]))
{
//the current index is a vowel, take the text from the last read index to this index
noVowels.Append(name, lastIndex, i - lastIndex);
lastIndex = i + 1;
}
}
if (lastIndex < i)
{
//the last character wasn't a vowel so we need to add the rest of the string here.
noVowels.Append(name, lastIndex, name.Length - lastIndex);
}
return noVowels.ToString();
}
The above method can be called for each name in your array:
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine("The output is:" + RemoveVowels(names[i]));
}
As to which approach to use, I would go with the one you find the most readable unless you have some specific performance requirements at which point I think you'd need to measure each approach and pick the one that fits your requirements best.