删除字符“ |”之前的字符

时间:2020-07-08 17:34:25

标签: c#

我有一个软件,需要删除“ |”之前的所有字符。 例如输入

“文本需要删除|文本需要保留”

示例输出为

“文字需要保留”

我的代码如下。它适用于单行文本,但不适用于多行。 (仅删除第一行上的文本,其余部分保持不变)

我需要使其与多行一起使用。有什么想法吗?

 string input = richTextBox.Text;

  
  
 string output = input.Substring(input.IndexOf('|') + 1);

 richTextBox1.Text = output;
   

4 个答案:

答案 0 :(得分:2)

您可以使用Lines属性和临时List<string>轻松地存储子字符串的结果

List<string> newLines = new List<string>();
foreach (string s in richTextBox1.Lines)
{
    // If you want only the lines with the | remove the else block
    int x = s.IndexOf('|');
    if(x > -1)
        newLines.Add(s.Substring(x + 1).Trim());
    else
        newLines.Add(s);
}
richTextBox1.Lines = newLines.ToArray();

答案 1 :(得分:0)

string output = "";        
var myArray = input.Split("\r\n");
        
        foreach(var ar in myArray)
            if(ar.Length > 0)
             output+= ar.Substring(0, ar.IndexOf('|')) + "\r\n";

糟糕!我返回了第一部分,但我想您已经明白了

答案 2 :(得分:0)

为此使用LINQ怎么办。 例如:

List<string> lines = yourString.Split("\n"); //Add \r if needed
List<string> smallerLines = lines.Select(x => x.Skip(x.IndexOf('|')+1));

如果需要,您总是可以在输出中创建一个新字符串:

string finalString = String.Join(String.Empty, smallerLines);

答案 3 :(得分:0)

        string input = richTextBox1.Text;
        int len = richTextBox1.Lines.Length;
        string output = "";
 
        for (int i = 0; i <len; i++)
        { 
            if(i!=len-1)
            {
                output += richTextBox1.Lines[i].Substring(input.IndexOf('|') + 1) +
                Environment.NewLine;
            }
            else
            {
                output += richTextBox1.Lines[i].Substring(input.IndexOf('|') + 1);
            }

            
        }
        richTextBox1.Text = output;
相关问题