插入字符串中的某个位置

时间:2014-08-19 02:11:54

标签: c# string

我发现this question将字符插入字符串中的某个位置,但是可以将字符插入到可变长度的字符串中吗?

例如;我想将子字符串s = c + separator插入到现有字符串中,如下所示:

string c = "C"; string separator = "-";
                                              {s}
string1 = "MOT1-G-PRT45-100"; // "MOT1-G-PRT45-C-100"

或者像这样:

string c = "C"; string separator = null;
                                        {s}     
string2 = "MOT1GPRT45100"; // "MOT1GPRT45C100"

我查看了string.Insert方法,但我认为在这种情况下我不能使用它。有没有人有我可以使用的任何其他建议?

注意:字符串中唯一保持不变的部分是总是是字符串末尾的3位数字。

3 个答案:

答案 0 :(得分:0)

这应该有效:

string s = "MOT1-G-PRT45-100";
int index = ... // position to insert
string res = s.Insert(index, c + separator);

答案 1 :(得分:0)

这样做;

string c = "C"; string separator = "-";

string string1 = "MOT1-G-PRT45-100";

int position = 13;

string string2 = string1.Insert(position, string.Format("{0}{1}", c, separator));

答案 2 :(得分:0)

如果最后总会有一个3位数字,那么就像这样简单:

string string1 = "MOT1-G-PRT45-100";
string c = "C", s = "-";
string1 = string1.Insert(string1.length-4,c+separator);
相关问题