'I can't remove vowel letters in string
using System;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
string str = "hello world";
char[] liste = { 'a','e','i','o','u'};
foreach (var vowel in liste)
{
str = str.Replace(vowel, string.Empty);
}
}
}
}
I want to remove vowel letters, i can do with with string array but i want to do it with char array as you see. But i have an error: argument2: cannot convert from 'string' to 'char'. I did not get why i can't use it.
Solution 1:[1]
Might I suggest using a different approach? The algorihm you've shown has a complexity of O(str.Length * liste.Length)
If you just care about the vowels, I suggest using a regex:
// remove ignore case if you only want to remove lowercase aeiou
private static readonly Regex vowelRegex = new(@"[aeiou]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static string RemoveVowels(string input) => vowelRegex.Replace(input, "");
If you want to have a more generic solution, there's a quick and dirty one below. It could be made more efficient, but both of these solutions will have a better complexity than the original.
public static string RemoveCharacters(IEnumerable<char> input, IEnumerable<char> charactersToRemove)
{
var set = charactersToRemove as IReadOnlySet<char>;
set ??= charactersToRemove.ToHashSet();
return RemoveCharacters(input, set);
}
public static string RemoveCharacters(IEnumerable<char> input, IReadOnlySet<char> charactersToRemove)
{
StringBuilder builder = new();
foreach (char c in input)
{
if (!charactersToRemove.Contains(c))
{
builder.Append(c);
}
}
return builder.ToString();
}
Solution 2:[2]
You could use a rather straight-forward approach for removing vowels without the use of string.Replace(). This suggestion uses Linq, and works as follows:
- filter the content of
strinto achar collectiononly containing characters that are not present inliste:
var filteredCharacters = str.Where(ch => !liste.Contains(ch));
- concatenate the filtered
char collectioninto the resulting string, usingstring.Join()with an empty separator:
str = string.Join(string.Empty, filteredCharacters);
Writing the two operations inline, the following code
string str = "hello world";
char[] liste = { 'a', 'e', 'i', 'o', 'u' };
str = string.Join(string.Empty, str.Where(ch => !liste.Contains(ch)));
Console.WriteLine(str);
produces
hll wrld
Example fiddle here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Astrid E. |
