Leon Barkan Leon Barkan - 2 months ago 9
C# Question

How to Change many char's combination's to one of that kind

In my application I want to edit string (Make many instances as one)

For example I have string:

string str = "/r/n/r/n/r/n Some text /r/n/r/n/r/n 45678123";


The wanted result:

"/r/n Sometext /r/n 45678123";


Function like:

string newStr = str.MakeToOneInstance("/r/n");


I need to make it dynamic (in my example I don't know how many /r/n combinations I have)

It can be any combination one more example ->
"dodo you have an answer";


string newStr = str.MakeToOneInstance("do"); -> "do you have an answer";


I know I can make string extension Method that will use regular expression but the question if I have something like that build in .Net or maybe original way to perform that...

Answer

You can use Regex.Replace(input, @"(?:\r\n){2,}", Environment.NewLine)

This will replace multiple occurences of \r\n by a single new line.


You can put this in an extension like so:

public static class MyExtensions
{
    public static string MakeToOneInstance(this String str, string toReplace)
    {
        return Regex.Replace(str, string.Format("\\b(?:{0}){1}\\b", Regex.Escape(toReplace), "{2,}"), toReplace);
    }
}   

And use it as you wanted to.

Example:

"oooooo loop".MakeToOneInstance("o")
"o loop"