Ricky Ricky - 1 month ago 20
C# Question

How do I remove all tabs BEFORE a string (not after) efficiently?

I have a large text file I'm trying to parse. In order to parse this file I need to remove ALL tabs before a string, but not after.

So for example...

string sample = "\t\t\tThis is a string \t with a tab";
sample = RemoveInitialTabs(sample);
// sample should now be "This is a string \t with a tab";

I currently do this by reading in the file into an array (delimited by newline characters), iterating through a each line, and then for each line I adjust the string until a non tab character is reached like so....

for (int i = file_content.Count - 1; i > -1; i--)
// Remove initial tabs...
int size = 0;
for (int j = 0; j < file_content[i].Length; j++)
if (file_content[i][j] != '\t')
size = j + 1;

if (size > 0)
file_content[i] = file_content[i].Remove(0, size);

This works, but it is very slow (due to the size of the content in the file, a run typically takes about 66,453ms ONLY to remove the tabs)....

Any ideas?


I think what could help you is TrimStart(params char[] trimChars) MSDN Link

For example you can use this:

sample = sample.TrimStart(new char[] {'\t'});

The output of this would be as desired.