string.insert multiple values. Is this possible?

2019-05-11 09:22发布

Im still learning in C#, and there is one thing i cant really seem to find the answer to.

If i have a string that looks like this "abcdefg012345", and i want to make it look like "ab-cde-fg-012345"

i tought of something like this:

  string S1 = "abcdefg012345";
            string S2 = S1.Insert(2, "-");
            string S3 = S2.Insert(6, "-");
            string S4 = S3.Insert.....
                ...
                ..

Now i was looking if it would be possible to get this al into 1 line somehow, without having to make all those strings.

I assume this would be possible somehow ?

标签: c# string insert
8条回答
看我几分像从前
2楼-- · 2019-05-11 10:13

I like this

    StringBuilder sb = new StringBuilder("abcdefg012345");
    sb.Insert(6, '-').Insert(2, '-').ToString();
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-05-11 10:14

If the positions for the inserted strings are constant you could consider using string.Format() method. For example:

string strTarget = String.Format("abc{0}def{0}g012345","-");
查看更多
登录 后发表回答