按长度删除子字符串

时间:2012-09-04 17:31:05

标签: c# substring

我一直在尝试在开头或结尾删除特定长度的子字符串。

这是我编写的代码但不起作用。

this.temp = String.Empty;
foreach (string line in this.txtBox.Lines) {
    if (Envir.Operations.Begin == true)
        this.temp += line.Substring(Envir.Operations.Length - 1) + Environment.NewLine;
    else
        this.temp += line.Substring(0, line.Length - Envir.Operations.Length) + Environment.NewLine;
}

如果你知道如何解决这个问题,你会非常友好地告诉我吗?

非常感谢!

2 个答案:

答案 0 :(得分:0)

line.Substring必须有两个参数,即子串的起始索引和长度

替换为

 if (Envir.Operations.Begin)
 {
   this.temp += line.Substring(0, Envir.Operations.Length - 1) + Environment.NewLine;
 }

答案 1 :(得分:0)

您的代码看起来不错,但它不会检查输入字符串是否比您需要的长度长。它可能导致超出范围的异常。像这样修改你的代码:

    this.temp = String.Empty;
foreach (string line in this.txtBox.Lines) {
    if (line.Length<=Envir.Operations.Length) {
        this.temp += Environment.NewLine;
        continue; // adding new line if input is shorter
    }
    if (Envir.Operations.Begin)
        this.temp += line.Substring(Envir.Operations.Length - 1) + Environment.NewLine;
    else
        this.temp += line.Substring(0, line.Length - Envir.Operations.Length) + Environment.NewLine;

}

相关问题