C# - 根据插入位置

时间:2016-01-14 03:11:18

标签: c# winforms richtextbox

我有一个RichTextBox,此处称为box

string currentline = box.Lines[box.GetLineFromCharIndex(box.SelectionStart)];

那条线取出了插入符号所在的行。它非常有用。

但是,我需要从中获取两个字符串。第一个是插入插入符号的那一行,第二个是它后面的所有内容。

例如,如果该行为How is you|r day going?|代表插入符号,我会分别获得How is your day going?

我写了这个怪物,有效:

string allbefore = box.Text.Substring(0, box.SelectionStart);
string allafter = box.Text.Substring(box.SelectionStart, box.Text.Length - box.SelectionStart);
string linebefore = "";
for (int i = 0; i < allbefore.Length; i++)
{
    linebefore += allbefore[i];
    if (allbefore[i] == '\n')
        linebefore = "";
}
string lineafter = "";
for (int i = 0; i < allafter.Length; i++)
{
    if (allafter[i] == '\n')
        break;
    else
        lineafter += allafter[i];
}

它给了我想要的结果,但是涉及在整个框中循环遍历每个角色,这只是伤害。有一种简单的方法可以做到这一点我只是缺席了吗?感谢。

3 个答案:

答案 0 :(得分:1)

您是否尝试过使用line.split?不确定这是不是你想要的。

答案 1 :(得分:1)

这可能会为你做到这一点

"General Error"

在第一种方法中,我们按字符public partial class Form1 : Form { //some method ... try { FolderInfo newFolder = CommonCreative.CreateFolder(textFolderName.Text); } catch (Exception ex) { textBoxResult.Parent.Invoke((MethodInvoker)delegate { textBoxResult.AppendText("General Error"); textBoxResult.AppendText(Environment.NewLine); }); } //... public void update(string message) { textBoxResult.Parent.Invoke((MethodInvoker)delegate { textBoxResult.AppendText(message); textBoxResult.AppendText(Environment.NewLine); }); } } public static class CommonCreative { public static FolderInfo CreateFolder(string foldername) { try { // return folder; } catch (Exception ex) { // Failed - return null error = ex.Message; Form1._Form1.update("Error from the CommonCreative class"); return null; } } } 拆分行,而不是查找是否有string currentline = box.Lines[box.GetLineFromCharIndex(box.SelectionStart)]; var listOfStrings = new List<string>(); string[] splitedBox = currentline.Split('|'); foreach(string sp in splitedBox) { string[] lineleft = sp.Split('\n'); listOfStrings.Add(lineleft[lineleft.Count() - 1]); } 如果它存在,我们会相应地取值

另一种方法可能是

|

在第二种方法中,我们删除\n之前和之后的字符,然后拆分字符串。我认为第二个对我来说似乎更好。

答案 2 :(得分:0)

使用\n存储indexOf的位置,如果&gt; = 0,即字符串包含它,请使用substring并分配值。

string allbefore = box.Text.Substring(0, box.SelectionStart);
string allafter = box.Text.Substring(box.SelectionStart, box.Text.Length - box.SelectionStart);
int newLinePos = allBefore.lastIndexOf("\n");
string lineBefore = ((newLinePos >= 0) ? (allBefore.substring(newLinePos + 1)) : (allBefore));
    newLinePos = allafter.indexOf("\n");
string lineAfter = ((newLinePost >= 0) ? (allAfter.substring(0, newLinePos)) : (allAfter));
相关问题