插入到字符串中的某个位置
本文关键字:位置 字符串 插入 | 更新日期: 2023-09-27 18:18:39
我发现这个问题插入字符到一个字符串的某个位置,但是有可能插入一个字符到一个字符串,是一个可变长度?
例如;我想将子字符串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位数
应该可以:
string s = "MOT1-G-PRT45-100";
int index = ... // position to insert
string res = s.Insert(index, c + separator);
可以;
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));
如果最后总是有一个3位数的数字,那么它将像这样简单:
string string1 = "MOT1-G-PRT45-100";
string c = "C", s = "-";
string1 = string1.Insert(string1.length-4,c+separator);