- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在各种文本编辑器中,您可能都知道使用键盘快捷键 (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/
如何使用 tabulate 包在 python 中合并多个表? append 在 python 中连接两个表时不起作用。这些表是使用 python 中的 tabulate 包实现的。 table_1
我想使用制表法将两个表格并排显示。 我的方法: test_table1 = tabulate([['Alice', 24], ['Bob', 19]]) test_table2 = tabulate(
我之前在大学学习过 Java 的为期 3 个月的短期类(class)(唯一的项目是编写数独游戏)。 我想学习一种对于一般自动化任务来说最流行的编程语言。到目前为止,我已经选择了 AHK,它帮助我完成了
我的脚本有问题.. 用户需要向一个 div 输入数据,当一个 div 已满(4 个字符)时,脚本应自动移动到下一个字段。 在处理输入时,这非常有效: http://jsfiddle.net/4m5fg
我正在使用 MySQL Workbench 来编写一些查询。我想设置 MySQL 编辑器,以便在按 Enter 键换行时在下一行中保持对齐或水平制表。就像编程编辑通常所做的那样,我想你就是我的意思。
我正在尝试:(1) 估计只有因变量发生变化的多个模型 (2) 使用 Stargazer 包将结果制表 以下代码有效,但我必须为每个模型重复一行代码: library(stargazer)
我是一名优秀的程序员,十分优秀!