Home > Blockchain >  I can't remove vowel letters in string
I can't remove vowel letters in string

Time:03-21

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.

CodePudding user response:

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();
}

CodePudding user response:

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:

  1. filter the content of str into a char collection only containing characters that are not present in liste:
var filteredCharacters = str.Where(ch => !liste.Contains(ch));
  1. concatenate the filtered char collection into the resulting string, using string.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.

  • Related