Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Remove tab from string, Tabs Identificaton

Tags:

c#

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.

like image 736
Kamran Avatar asked Oct 27 '14 09:10

Kamran


1 Answers

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, " "); 
like image 193
Morbia Avatar answered Oct 11 '22 19:10

Morbia