空格(文本框)

本文关键字:文本 空格 | 更新日期: 2023-09-27 18:14:56

在c#中我知道这个

 if (textBox1.Text.Length > x)
    {
        textBox1.AppendText(Environment.NewLine);
    }

(x是某个随机数)但是如果我想在x之前的第一个空格上中断呢?

空格(文本框)

我想你的问题是:

我想在最靠近"x"的空间插入新行,该空间的索引不超过"x"。

那么给定这个例子:

敏捷的棕色盒子跳过了懒惰的狗。

并且"X"是30,那么我希望在"jump "answers"over"之间插入新行。

我想这对你会有用:

var str = "The quick brown box jumped over the lazy dog.";
var x = 30;
var index = str.Select((c, i) => new {c, i}).TakeWhile(q => q.i < x).Where(q => q.c == ' ' ).Select(q => q.i).Last();
var formatted = str.Insert(index, Environment.NewLine);

其中formatted包含带换行符的新字符串。注意,如果字符串中根本没有空格,Last()将给出一个异常。在这种情况下,使用LastOrDefault并适当处理。

根据你的例子:

var x = 30;
if (textBox1.Text.Length > x) 
{
    var index = textBox1.Text.Select((c, i) => new {c, i}).TakeWhile(q => q.i < x).Where(q => q.c == ' ' ).Select(q => q.i).Last(); 
    textBox1.Text = textBox1.Text.Insert(index, Environment.NewLine);
} 

或者直接使用LastIndexOf重载:

var current = textBox.Text;
textBox.Text = current.Insert(current.LastIndexOf(' ', 24), Environment.NewLine);

LastIndexOf将从位置24开始搜索,将向后移动,直到接近第一个' '

' '第一次出现的位置插入Environment.NewLineUPDATE添加SubString(0,X)以满足位置X前一个空格的要求

textBox1.Text.Insert(textBox1.Text.SubString(0,X).IndexOf(' '), Environment.NewLine);

看看是否有帮助:

            string text = "this is a long sentence";
            int x = 10;
            string updatedtext = string.Empty;
            updatedtext = text.Insert((x - 1) - text.Substring(0,x).Reverse().ToString().IndexOf(' '),Environment.NewLine);

用合适的变量替换你的文本框

如果x = 20,并且文本框中包含字符串:

    Lorem ipsum dolor sit amet, consectetur adipisicing elit.

那么下面的代码将返回:

    Lorem ipsum dolor 
    sit amet, consectetur adipisicing elit
if (textBox1.Text.Length > x)
{
    int lastSpaceIndex = textBox1.Text.LastIndexOf(' ', x-1, x);
    if (lastSpaceIndex < 0)
        lastSpaceIndex = x;
    textBox1.Text.Insert(lastSpaceIndex, Environment.NewLine);
}

编辑根据下面Mithun的评论更正。