Reputation: 141
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 ?
Upvotes: 0
Views: 306
Reputation: 76
Whenever you perform any operation on a string data type, it creates a new string which you have to store in a new variable.
Upvotes: 0
Reputation: 37299
.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();
If you need to deal with replacement when insensitive then look at: Is there an alternative to string.Replace that is case-insensitive?
Upvotes: 4
Reputation: 76
static void Main(string[] args)
{
string[] musicinst = new string[4] { "cello", "guitar", "violin", "double bass" };
char[] vowels = new char[5] { 'a', 'e', 'i' ,'o', 'u' };
List<string> output = new List<string>();
foreach (string s in musicinst)
{
string s1 = s;
foreach (var v in vowels)
{
if (s1.Contains(v))
{
s1=s1.Remove(s1.IndexOf(v),1);
}
}
output.Add(s1);
}
Console.ReadLine();
}
Upvotes: 2
Reputation: 19765
You're running into a feature of C# strings called immutability - operations on strings do not change the string, it returns a new string. given this, you might think you need to do this:
s = s.Replace("s", "o");
But that won't work because 's' is a foreach iterator. Your best bet is to recast your loop:
for (int i = 0; i < musicinst.Length; ++i)
{
if (musicinst[i].Contains("s"))
{
musicinst[i] = musicinst.Replace("s", "o");
}
}
Which will change your array in-place. To preserve immutability of the array as well you might consider a LINQ-like option that builds a new array as others have demonstrated.
Upvotes: 3