Reputation: 4100
I want to remove tabs from a string. I am using this code but its not working.
string strWithTabs = "here is a string with a tab";
// tab-character
char tab = '\u0009';
String line = strWithTabs.Replace(tab.ToString(), "");
I tried this, but still its not working
String line = strWithTabs.Replace("\t", "");
It worked with String line = strWithTabs.Replace(" ", "");
But is their any other way to Identify tabs ?
I also looked at this post Removal of Tab-whitespace? But it removed all the spaces from the string, where as I just want to remove Tabs.
Upvotes: 31
Views: 99230
Reputation: 21
Seems to be the compactest ...
//Eliminate tabs & multiple spaces => only 1 space between words
string input1 = " Hello World !";
Regex rgx2 = new Regex("\t|\\s+");
string result = rgx2.Replace(input1, " ");
Console.WriteLine("Original String: {0}", input1);
Console.WriteLine("Replacement String: {0}", result);
Console.ReadKey();
~~~
Upvotes: 2
Reputation: 4344
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, " ");
Upvotes: 40
Reputation: 101
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, " ");
Upvotes: 9
Reputation: 98760
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.
Upvotes: 31