I have a string value
string text = "-----------------\r\n Some text here Some text here\r\n"
Is there a way to remove 2 spaces in each place where are many spaces?
Thank you, for your help
I have a string value
string text = "-----------------\r\n Some text here Some text here\r\n"
Is there a way to remove 2 spaces in each place where are many spaces?
Thank you, for your help
You can use regex.
var result = new Regex("\s{2,}").Replace(text,constForWhiteSpace)
Regex regex = new Regex(@"[ ]{2,}"); // Regex to match more than two occurences of space
text = regex.Replace(text, @"");
edit: this is for speed, otherwise regex as suggested by other answers is fine. This function is very fast.
edit 2: just remove \r \n if you want to keep new lines.
public static String SingleSpacedTrim(String inString)
{
StringBuilder sb = new StringBuilder();
Boolean inBlanks = false;
foreach (Char c in inString)
{
switch (c)
{
case '\r':
case '\n':
case '\t':
case ' ':
if (!inBlanks)
{
inBlanks = true;
sb.Append(' ');
}
continue;
default:
inBlanks = false;
sb.Append(c);
break;
}
}
return sb.ToString().Trim();
}
Try it....
string _str = "-----------------\r\n Some text here Some text here\r\n";
_str = _str.Trim();
Console.WriteLine(_str.Replace(" ",""));
Output :
SometexthereSometexthere
Try this:
var result = new Regex("\s{2,}").Replace(text,string.Empty)
var dirty = "asdjk asldkjas dasdl l aksdjal;sd asd;lkjdaslj";
var clean = string.Join(" ", dirty.Split(' ').Where(x => !string.IsNullOrEmpty(x)));
If you don't like Regex or the text is large you can use this extension:
public static String TrimBetween(this string text, int maxWhiteSpaces = 1)
{
StringBuilder sb = new StringBuilder();
int count = 0;
foreach (Char c in text)
{
if (!Char.IsWhiteSpace(c))
{
count = 0;
sb.Append(c);
}
else
{
if (++count <= maxWhiteSpaces)
sb.Append(c);
}
}
return sb.ToString();
}
Then it's simple as:
string text = "-----------------\r\n Some text here Some text here\r\n";
text = text.TrimBetween(2);
Result:
-----------------
Some text here Some text here
Not the nicest piece of code but this should remove two whitespaces from the text if you want to use a regex.
//one.two..three...four....five..... (dots = spaces)
string input = "one two three four five ";
string result = new Regex(@"\s{2,}").Replace(input, delegate(Match m)
{
if (m.Value.Length > 2)
{
int substring = m.Value.Length - 2;
//if there are two spaces, just remove the one
if (m.Value.Length == 2) substring = 1;
string str = m.Value.Substring(m.Value.Length - substring);
return str;
}
return m.Value;
});
Output would be
//dots represent spaces. Two spaces are removed from each one but one
//unless there are two spaces, in which case only one is removed.
one.two.three.four..five...
You can use String.Replace function:
text=text.Replace(" "," ");
But remember you are supposed to research a bit your request before posting: this is very basic stuff.