C# preg_replace?

前端 未结 5 1543
猫巷女王i
猫巷女王i 2020-12-10 09:46

What is the PHP preg_replace in C#?

I have an array of string that I would like to replace by an other array of string. Here is an example in PHP. How can I do somet

5条回答
  •  感动是毒
    2020-12-10 09:58

    Edit: Uhg I just realized this question was for 2.0, but I'll leave it in case you do have access to 3.5.

    Just another take on the Linq thing. Now I used List instead of Char[] but that's just to make it look a little cleaner. There is no IndexOf method on arrays but there is one on List. Why did I need this? Well from what I am guessing, there is no direct correlation between the replacement list and the list of ones to be replaced. Just the index.

    So with that in mind, you can do this with Char[] just fine. But when you see the IndexOf method, you have to add in a .ToList() before it.

    Like this: someArray.ToList().IndexOf

      String text;
      List patternsToReplace;
      List patternsToUse;
    
      patternsToReplace = new List();
      patternsToReplace.Add('a');
      patternsToReplace.Add('c');
      patternsToUse = new List();
      patternsToUse.Add('X');
      patternsToUse.Add('Z');
    
      text = "This is a thing to replace stuff with";
    
      var allAsAndCs = text.ToCharArray()
                     .Select
                     (
                       currentItem => patternsToReplace.Contains(currentItem) 
                         ? patternsToUse[patternsToReplace.IndexOf(currentItem)] 
                         : currentItem
                     )
                     .ToArray();
    
      text = new String(allAsAndCs);
    

    This just converts the text to a character array, selects through each one. If the current character is not in the replacement list, just send back the character as is. If it is in the replacement list, return the character in the same index of the replacement characters list. Last thing is to create a string from the character array.

      using System;
      using System.Collections.Generic;
      using System.Linq;
    

提交回复
热议问题