大家都可能知道键盘快捷键(Shift Tab)以删除各种文本编辑器中多行的标签或空间。我想用C#中的字符串来做到这一点。
我知道如何以非常不优化的方式进行操作,但不是很大的错误。但是,是否有一些"简单"的方法可以做到这一点,例如带有正则表达式或一些优化的代码,可以使用?
,但要点是从一开始就删除一个tabstop。
有些黑客介绍了代码的想法:
string textToEdit = "Some normal textrn" +
"tText in tabrn" +
" Text in space tabrn" +
" t Text in strange tabrn" +
"tttMultiple tabsrn" +
" 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);
输出应为:
Some normal text
Text in tab
Text in space tab
Text in strange tab
Multiple tabs
Not quite a tab
这是一种可以执行我认为您原始代码打算执行的方法,即从行的开头删除多达4个空格,或一个Tab字符,而忽略其他空间空格字符:
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);
}
实际上,它可以称为:
string textToEdit = "Some normal textrntText in tabrn Text in space tabrn" +
" tText in strange tabrntttMultiple tabsrn Not quite a tab";
var result = string.Join(Environment.NewLine, textToEdit
.Split(new[] {Environment.NewLine}, StringSplitOptions.None)
.Select(RemoveLeadingTab));