c# string.replace in foreach loop

后端 未结 5 1720
长发绾君心
长发绾君心 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:35

    Why use replace, this will make the application slow. Use regex:

    http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx

    0 讨论(0)
  • 2021-02-07 14:47

    As others have mentioned you'd need to use a for loop to do this in-place. However, if you don't need the operation to be done in-place (i.e. the results can be a different collection), then you could also do it as a linq query, e.g.

    var results = from name in names select name.Replace("pdf", "txt");
    

    One thing though - it looks like you are trying to change the extension of some file names. If that's what you are trying to do then I'd recommend Path.ChangeExtension which is specifically designed for this purpose.

    var results = from name in names select Path.ChangeExtension(name, "txt");
    
    0 讨论(0)
  • 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");
    }
    
    0 讨论(0)
  • 2021-02-07 14:57

    s.Replace is a function so you would like s=s.Replace().. although it's better to use StringBuilder. (see upper answer)

    0 讨论(0)
  • 2021-02-07 14:59

    You say you're after a LINQ solution... that's easy:

    var replacedNames = names.Select(x => x.Replace("pdf", "txt"));
    

    We don't know the type of names, but if you want to assign back to it you could potentially use ToArray or ToList:

    // If names is a List<T>
    names = names.Select(x => x.Replace("pdf", "txt")).ToList();
    // If names is an array
    names = names.Select(x => x.Replace("pdf", "txt")).ToArray();
    

    You should be aware that the code that you've posted isn't using LINQ at all at the moment though...

    0 讨论(0)
提交回复
热议问题