📜  C#字符串Insert()方法(1)

📅  最后修改于: 2023-12-03 14:40:32.965000             🧑  作者: Mango

C#字符串Insert()方法

Insert()方法是C#中字符串类的一个方法,它用于将一个字符串插入到当前字符串的指定位置。Insert()方法可以非常方便地在字符串中插入子字符串,从而实现字符串的修改和处理。Insert()方法的语法如下:

public string Insert(int startIndex, string value);

其中,startIndex表示要插入字符串的位置,value表示要插入的字符串。

Insert()方法的返回值是修改后的新字符串。

使用示例

下面是一些使用Insert()方法的示例代码:

string str = "Hello, World!";
string newStr = str.Insert(5, "my ");
Console.WriteLine(newStr);

上面的代码将在"Hello, World!"的第5个位置插入"my ",输出结果为"Hello, my World!"。

string str = "Hello, World!";
string name = "Jack";
string newStr = str.Insert(7, name);
Console.WriteLine(newStr);

上面的代码将在"Hello, World!"的第7个位置插入"Jack",输出结果为"Hello, Jack World!"。

string str = "1,2,3";
string newStr = str.Insert(3, ",4");
Console.WriteLine(newStr);

上面的代码将在"1,2,3"的第3个位置插入",4",输出结果为"1,2,4,3"。

注意事项
  • Insert()方法返回的是新的字符串,源字符串并不会被修改。
  • 如果插入字符串的位置超出了源字符串的长度,Insert()方法会抛出ArgumentOutOfRangeException异常。
  • 如果插入的字符串是null,则Insert()方法会将其视为一个空字符串插入到源字符串中。
总结

Insert()方法是C#中字符串类非常实用的一个方法,它允许我们在源字符串中非常方便地插入新的字符串,实现字符串的修改和处理。我们可以使用Insert()方法在指定位置插入需要的字符串,同时注意一些需要注意的事项。