试图删除C#中的一些字符串

时间:2017-03-09 18:09:01

标签: c#

我正在努力做到这一点:

G0E1X.52Y-.48M3S6000
H1Z-.2M8
G1Z.005F20.
X-6.82F18.
Y-.04
X.56
G0Z.2

看起来像这样:

E2X.52Y-.48
G1Z.005F20.
X-6.82F18.
Y-.04
X.56
G0Z.2

对于我制作的每个其他副本,“E”之后的数字将增加1(E3,E4,E5等),而其余文本将保持不变。

到目前为止,我有这个,虽然它有效,但我想知道是否有更好的方法来做到这一点。

注意:Preview.Text包含更多文本。但是,在执行下面显示的代码后,字符串“DynamicPart”仅包含上面显示的示例。

            string Part = Preview.Text;
            int PartStart = Preview.Text.IndexOf("M6");
            int PartFinish = Preview.Text.IndexOf("M6", PartStart + 1);
            int PartLength = PartFinish - PartStart;
            Part = Preview.Text.Substring(PartStart, PartLength);
            int PartToolInfo = Part.IndexOf("E1", 0);
            Part = Part.Remove(0, PartToolInfo + 2);
            int PartM1 = Part.IndexOf("M");
            int PartM2 = Part.IndexOf("M", PartM1 + 1);
            Part = Part.Remove(PartM1, PartM2 - PartM1 + 2);
            string DynamicPart = Part;

            for (int x = 2; x <= Convert.ToInt32(NumberOfParts.Text); x++)
            {
                DynamicPart = Part.Insert(0, "E" + x);
                Preview.Text = Preview.Text.Insert(PartFinish, DynamicPart);
                PartFinish = Preview.Text.IndexOf("M6", PartStart + 1);
            }

1 个答案:

答案 0 :(得分:0)

尝试这样的事情

using System;

public class RemoveTest {
public static void Main() {

    string name = "Michelle Violet Banks";

    Console.WriteLine("The entire name is '{0}'", name);

    // remove the middle name, identified by finding the spaces in the middle of the name...
    int foundS1 = name.IndexOf(" ");
    int foundS2 = name.IndexOf(" ", foundS1 + 1);

    if (foundS1 != foundS2 && foundS1 >= 0) {

        name = name.Remove(foundS1 + 1, foundS2 - foundS1);

        Console.WriteLine("After removing the middle name, we are left with '{0}'", name);
    }
  }
}
// The example displays the following output:
//       The entire name is 'Michelle Violet Banks'
//       After removing the middle name, we are left with 'Michelle Banks'