c# string.replace in foreach loop

后端 未结 5 1722
长发绾君心
长发绾君心 2021-02-07 14:01

Somehow I can\'t seem to get string replacement within a foreach loop in C# to work. My code is as follows :

foreach (string s in names)
{
    s.Replace(\"pdf\"         


        
5条回答
  •  野的像风
    2021-02-07 14:56

    Strings in C# are immutable (does not change), so s.Replace will return a new string. Unfortunately this means you cannot use foreach to do the update. If names is an array this should work:

    for(int i = 0; i < names.Length; i++)
    {
        names[i] = names[i].Replace("pdf", "txt");
    }
    

提交回复
热议问题