Count and replace all vowels in the text box

I need to count all the vowels and replace it with the letter x in the text box. I managed to make the counting part, and here is the code, but I have a problem with replacing all the vowels in the text box with the letter x. Can anybody help me?

int total = 0;

string sentence = textBox1.Text.ToLower();
char[] vowels = { 'a', 'e', 'i', 'o', 'u', 'y'};                   
{
      total++;
}

total = sentence.Count(c => vowels.Contains(c));
MessageBox.Show("There are " + total++ " vowels";

for (int i = 0; i < sentence.Length; i++)

EDIT 1 :

Thank you all for your help. For some reason, the vowels in my text box do not change !!! It does the counting, but does not replace the letter x. I tried all the solutions here, but so far nothing has happened with my vowels in the text box.

+4
source share
5 answers
foreach(char vowel in vowels)
    sentence = sentence.Replace(vowel, 'x');

- !!! , . , .

. , , TextBox.Text. :

textBox1.Text = sentence; // after you have used Replace like shown above
+6

Linq:

sentence = string.Concat(sentence.Select(c => vowels.Contains(c) ? 'x' : c));
+4

:

var r = new Regex("[aeiouy]");
sentence = r.Replace(sentence, "x");

EDIT: , sentence , :

textBox1.Text = sentence;
+3

ForEach Linq -Expression string.Replace:

vowels.ToList().ForEach(vowel => sentence = sentence.Replace(vowel, 'x'));

1:

You can also try for-loop, as you also tried in your question:

for (int i = 0; i < sentence.Length; i++) {
    if(vowels.Contains((char)sentence[i])) {
        sentence[i] = 'x';
    }
}

EDIT 2:

To write the value sentenceback to TextBox, add the following:

textBox1.Text = sentence;
+1
source

Why not just try with regex, as the colleague above said?

Sort of:

string text = "This is the text";

        string vowels = @"([aeiou])";
        Regex regex = new Regex(vowels);

        Match match = regex.Match(text);

and then maybe continue your logic with some collection and a foreach () loop in which you do the replacement with char / string "x".

0
source

Source: https://habr.com/ru/post/1662531/


All Articles