C# Remove tab from string, Tabs Identificaton

Tab and space are not same, if tab is converted into spaces, replacing just "\t" will not work. Below code will find tab and replace with single space and also find multiple spaces and replace it with single space.

string strWithTabs = "here is a string          with a tab and with      spaces";

string line = strWithTabs.Replace("\t", " ");
while(line.IndexOf("  ") >= 0)
{
    line = line.Replace("  ", " ");
}

Edit: Since this is accepted, I'll amend it with the better solution posted by Emilio.NT which is to use Regex instead of while:

string strWithTabs = "here is a string          with a tab and with      spaces";
const string reduceMultiSpace= @"[ ]{2,}";
var line= Regex.Replace(strWithTabs.Replace("\t"," "), reduceMultiSpace, " ");

Because " " is not equal to tab character. \t is. It is an escape sequence character.

For example;

string strWithTabs = "here is a string\twith a tab";
char tab = '\u0009';
String line = strWithTabs.Replace(tab.ToString(), "");

line will be here is a stringwith a tab

You can't say a sentence like \t is equal to 6 spaces for example.


Use Regular Expression to reduce multiple spaces to one:

var strWithTabs = "here is a string      with a tab    and      spaces";
const string reduceMultiSpace= @"[ ]{2,}";
var line= Regex.Replace(strWithTabs.Replace("\t"," "), reduceMultiSpace, " ");

Tags:

C#