Omar Alaa Omar Alaa - 1 month ago 8
C# Question

c# Working with Strings

I'm Learning c# and i am making some exercises. i was asked to make a program that make an array of strings and remove the vowels form it's words
i did this code to remove the vowel "S" but it didn't work. can someone help me with that ?

string[] musicinst = new string[4] { "cello", "guitar", "violin", "double bass" };

foreach (string s in musicinst)
{
if (s.Contains("s")) { s.Replace("s", ""); }
Console.WriteLine(s);
}


now this code outputs the words exactly as i typed them in the array with no changes. so what is the problem here ?

Answer

.Replace does not change the string but returns a new string with the change. You need to now assign it back to s:

if (s.Contains("s")) 
{
    s = s.Replace("s", "o"); 
}

This will now also not work:

Cannot assign to 's' because it is a 'foreach iteration variable'

So instead use a for loop and access by indexer or create a new list and add the result of s.Replace to it:

string[] musicinst = new string[4] { "cello", "guitar", "violin", "double bass" };
var newData = musicinst.Select(item => item.Replace("s", "o")).ToArray();
Comments