Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert tabs to spaces in a .NET string

Tags:

string

.net

I am building a text parser using regular expressions. I need to convert all tab characters in a string to space characters. I cannot assume how many spaces a tab should encompass otherwise I could replace a tab with, say, 4 space characters. Is there any good solution for this type of problem. I need to do this in code so I cannot use an external tool.


Unfortunately, none of these answers address the problem with which I am encountered. I am extracting text from external text files and I cannot assume how they were created or which operating system was used to create them. I believe the length of the tab character can vary so if I encounter a tab when I am reading the text file, I want to know how many space characters I should replace it with.

like image 775
Arsalan Ahmed Avatar asked Feb 03 '09 17:02

Arsalan Ahmed


People also ask

How do I convert all my tabs to spaces?

Instead of changing tabs to spaces one by one, the Word's Find and Replace function is commonly used to convert tabs to spaces. Step 3: Enter a space character (press space button on your keyboard) in the Replace With field; Step 4: Click Replace All.

How do I convert tabs to spaces in Visual Studio?

Press the F1 key and type convert tabs to space or use the Ctrl+Shift+T key binding. This command convert all tabs to spaces. Actual tab size is read from the tabSize VS Code option.

What command is used to convert tabs to spaces?

To convert tabs to spaces, we use the expand command in the Linux system. If file is not given then the expand command read standard input.

How many spaces is a tab in C#?

The default is four spaces.


2 Answers

I am not sure if my solution is more efficient in execution, but it is more compact in code. This is close to the solution by user ckal, but reassembles the split strings using the Join function rather than '+='.

public static string ExpandTabs(string input, int tabLength)
{
    string[] parts = input.Split('\t');
    int count = 0;
    int maxpart = parts.Count() - 1;
    foreach (string part in parts)
    {
        if (count < maxpart)
            parts[count] = part + new string(' ', tabLength - (part.Length % tabLength));
        count++;
    }
    return(string.Join("", parts));
}
like image 96
DrWicked Avatar answered Sep 27 '22 23:09

DrWicked


I'm not sure how tabs will read in from a Unix text file, or whatever your various formats are, but this works for inline text. Perhaps it will help.

var textWithTabs = "some\tvalues\tseperated\twith\ttabs";
var textWithSpaces = string.Empty;

var textValues = textWithTabs.Split('\t');

foreach (var val in textValues)
{
    textWithSpaces += val + new string(' ', 8 - val.Length % 8);
}

Console.WriteLine(textWithTabs);
Console.WriteLine(textWithSpaces);
Console.Read();
like image 40
ckal Avatar answered Sep 28 '22 00:09

ckal