简体   繁体   中英

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 ?

.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?

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.

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

    }

每当您对字符串数据类型执行任何操作时,它都会创建一个新字符串,您必须将其存储在新变量中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM