If I have:
Some text
More text
Even more text
What is the more elegant way to obtain:
Some text
More text
Even more text
All with knowing the number of repeated tokens
If I have:
Some text
More text
Even more text
What is the more elegant way to obtain:
Some text
More text
Even more text
All with knowing the number of repeated tokens
Use regular expressions. Match the entire string '\r\n' and replace with a single '\r\n'
The function you need:
pattern = "(\\r\\n)+";
Regex rgx = new Regex(pattern);
newString = rgx.Replace(oldString, "\r\n");
EDIT: Apologies for missing the + earlier
Perhaps something like:
var result = string.Join("\r\n", s.Split(new[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries))
I don't know C# syntax, but just use a simple regex to replace (\r\n)+ with (\r\n)
The method to do so using regular expressions would be
string replaced = System.Text.RegularExpressions.Regex
.Replace(input, @"(?:\r\n)+", "\r\n");
(The (?:...)
syntax is a non-capturing group, which can be replaced with a capturing group (just (...)
), but that is slightly less efficient and not more readable, IMO.)
You can use a regular expression:
str = Regex.Replace(str, "(\r\n)+", "\r\n")
Another way could be to split on the line breaks removing empty entries, then join again:
str = String.Join("\r\n", str.Split(new string[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries);
Consider if you should use the string literal "\r\n"
or the Environment.NewLine
constant. That depends on where the data comes from.
If the \r\n means what it usually does, you're replacing successive blank lines with a single blank line.
I'm sure there are tools for that purpose. I wouldn't know about C#, though.
Without Regexs (which make my head hurt)
string RemoveRepeated(string needle, string haystack)
{
string doubleNeedle = needle + needle;
while (haystack.IndexOf(doubleNeedle) >= 0)
haystack = haystack.Replace(doubleNeedle, needle);
return haystack;
}
The fastest way:
Regex reg = new Regex(@"(\r\n)+");
string replacedString = reg.Replace("YOUR STRING TO BE REPLACED", Environment.NewLine);
Just a few days ago, there was nearly the same question around here in SO. There was not a NewLine the problem, instead it where whitespaces.
There was also the one guys who prefers the Split, Join method and the other site using a regex. So Jon made a comparison between both and it came out that a compile regex was much faster.
But i just can't find this question again...