Omar Alaa Omar Alaa - 1 year ago 85
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", ""); }

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

Answer Source

.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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download