gpt4 book ai didi

c# - 删除文本中多行的制表或空格

转载 作者:行者123 更新时间:2023-11-30 22:55:44 24 4
gpt4 key购买 nike

在各种文本编辑器中,您可能都知道使用键盘快捷键 (Shift + Tab) 删除制表符或多行空格。我想在 C# 中使用我的字符串执行此操作。

我知道如何以一种非常未经优化且不太容易出错的方式来做到这一点。但是有没有一些“简单”的方法来做到这一点,例如使用正则表达式,或者一些优化的代码剪下来使用?

但重点是只从开头删除一个制表位。

一些乱七八糟的代码想法:

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);

输出应该是:

Some normal text
Text in tab
Text in space tab
Text in strange tab
Multiple tabs
Not quite a tab

最佳答案

这是一种方法,可以执行我认为您的原始代码打算执行的操作,即从行首删除最多 4 个空格或一个制表符,同时忽略其他空白字符:

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 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));

关于c# - 删除文本中多行的制表或空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55011384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com