Ricky Ricky - 1 year ago 93
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download