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

入力文字列が必要な長さよりも長いかどうかをチェックしないことを除いて、コードは見栄えがします。範囲外の例外が発生する可能性があります。次のようにコードを変更します。

    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 に答える
0

line.Substring には、部分文字列の開始インデックスと長さの 2 つのパラメーターが必要です。

と置換する

 if (Envir.Operations.Begin)
 {
   this.temp += line.Substring(0, Envir.Operations.Length - 1) + Environment.NewLine;
 }
于 2012-09-04T17:32:30.533 に答える