You all probably know the keyboard shortcut (Shift + Tab) to remove tabulation or space of multiple lines in various text editors. I want to do this with my string in C#.
I know how to do it in a very unoptimized and not very error save way. But is there some "easy" way to do this e.g. with Regex, or some optimized code snipped to use out there?
But the point is to just remove one tabstop from the beginning.
Some hacked together idea of code:
string textToEdit = "Some normal text\r\n" +
"\tText in tab\r\n" +
" Text in space tab\r\n" +
" \t Text in strange tab\r\n" +
"\t\t\tMultiple tabs\r\n" +
" Not quite a tab";
int spacesInTabstop = 4;
string[] lines = textToEdit.Split('\n');
foreach (string line in lines)
{
int charPos = 0;
for (int i = 0; line.Length > 0 && i < spacesInTabstop + charPos; i++)
{
if (line[charPos] == '\t')
{
line = line.Remove(0, 1);
break; //Removed tab successfully
}
else if (line[charPos] == ' ')
{
line = line.Remove(0, 1); //Remove one of four spaces
}
else if (char.IsWhiteSpace(line[charPos]))
{
charPos++; //Character to ignore
}
else
break; //Nothing to remove anymore
}
}
textToEdit = string.Join("\n", lines);
The output should be:
Some normal text
Text in tab
Text in space tab
Text in strange tab
Multiple tabs
Not quite a tab
Here's a method that does what I think your original code is intending to do, which is to remove up to 4 spaces from the start of the line, or a tab character, while ignoring other whitespace characters:
private static string RemoveLeadingTab(string input)
{
var result = "";
var count = Math.Min(4, input?.Length ?? 0);
int index = 0;
for (; index < count; index++)
{
if (!char.IsWhiteSpace(input[index])) break;
if (input[index] == ' ') continue;
if (input[index] == '\t')
{
index++;
break;
}
if (char.IsWhiteSpace(input[index]))
{
result += input[index]; // Preserve other whitespace characters(?)
if (input.Length > count + 1) count++;
}
}
return result + input?.Substring(index);
}
In practice, it could be called like:
string textToEdit = "Some normal text\r\n\tText in tab\r\n Text in space tab\r\n" +
" \tText in strange tab\r\n\t\t\tMultiple tabs\r\n Not quite a tab";
var result = string.Join(Environment.NewLine, textToEdit
.Split(new[] {Environment.NewLine}, StringSplitOptions.None)
.Select(RemoveLeadingTab));