0

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

不过,这是我编写的代码,但无法正常工作。

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;
}

如果您知道如何解决此问题,请您告诉我吗?

非常感谢!

4

2 回答 2

0

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

用。。。来代替

 if (Envir.Operations.Begin)
 {
   this.temp += line.Substring(0, Envir.Operations.Length - 1) + Environment.NewLine;
 }
于 2012-09-04T17:32:30.533 回答
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;

}

于 2012-09-04T17:44:38.890 回答