【发布时间】:2017-07-24 15:02:31
【问题描述】:
我正在尝试制作一个 Reddit Formatter 工具,每当您有一个只有一个换行符的文本来添加另一个并创建一个新段落时。在 StackOverflow 中也是一样的,你必须按两次 Enter 键才能开始一个新段落。它来自:
Roses are red
Violets are Blue
到
Roses are red
Violets are Blue
下面的代码有效:它通过检查您在文本框中输入的文本中的每个字符来检测输入字符,从末尾开始,并在单击按钮后将它们替换为双字符
private void button1_Click(object sender, EventArgs e)
{
for (int i = textBox1.Text.Length - 1; i >= 0; i--)
{
if (textBox1.Text[i] == '\u000A')
{
textBox1.Text = textBox1.Text.Insert(i, "\r\n\r\n");
}
}
}
这很好,但如果它已经是一个双精度字符,我不想添加多个输入字符。我不想离开
Roses are red
Violets are Blue
到
Roses are red
Violets are Blue
因为它已经作为第一个示例工作了。如果你一直按下按钮,它只会无限增加更多的行。
我已经试过了:
private void button1_Click(object sender, EventArgs e)
{
for (int i = textBox1.Text.Length - 1; i >= 0; i--)
{
if (textBox1.Text[i] == '\u000A' && textBox1.Text[i - 1] != '\u000A')//if finds a SINGLE new line
{
textBox1.Text = textBox1.Text.Insert(i, "\r\n\r\n");
}
}
}
但它不起作用?基本相同,但还要检查前一个是否也是输入字符
我做错了什么?我真的很困惑,因为它应该可以工作......输出与第一个代码完全相同
提前谢谢你
【问题讨论】:
-
首先将
int i = textBox1.Text.Length - 1; i >= 0; i--改为int i = textBox1.Text.Length - 1; i > 0; i--,否则会抛出异常。 -
好的,非常感谢,现在修好了