C# 字符串 - Insert() 方法

C# 字符串 Insert() 方法用于返回一个新字符串,其中指定的字符串插入到此字符串实例的给定索引位置。

异常

此方法有几个异常 -

  • ArgumentNullException:当值为 null 时。
  • ArgumentOutOfRangeException:当 startIndex 为负数或大于字符串对象的长度时。

语法

以下是 C# 字符串 Insert() 方法的语法 -

public string Insert(int startIndex,字符串值);

参数

此方法接受以下参数 -

  • startIndex:表示当前字符串中将插入新值的索引位置。
  • value:表示要插入到指定位置的字符串。

返回值

此方法返回一个新字符串。它等于当前字符串对象。但该字符串已被修改,并在指定位置插入了一个值。

示例 1:插入空格

以下示例使用 Insert() 方法在字符串的第四个字符位置(即索引 3 处的字符)插入一个空格 -

    
using System;
public class Program {
   public static void Main()  {
      String original_str = "tutorialspoint";
      Console.WriteLine("The original string: '{0}'", original_str);
      // modify the string...
      String modified_str = original_str.Insert(3, " ");
      Console.WriteLine("The modified string: '{0}'", modified_str);
   }
}

输出

以下是输出 -

The original string: 'tutorialspoint'
The modified string: 'tut orialspoint'

示例 2:插入字符串

让我们看一下 Insert() 方法的另一个示例。在这里,我们定义一个字符串,并在该字符串的单词之间插入另一个字符串 -

using System;
public class Program {
   public static void Main() {
      String str = "Hello World!";
      String to_be_insert = "tutorialspoint";
      Console.WriteLine("The original string: '{0}'", str);
      // modify the string...
      String modified_str = str.Insert(3, to_be_insert);
      Console.WriteLine("The modified string: '{0}'", modified_str);
   }
}

输出

以下是输出 -

The original string: 'Hello World!'
The modified string: 'Heltutorialspointlo World!'

示例 3:在字符串开头插入

在此示例中,我们使用 Insert() 方法在字符串开头(具体为索引位置 0)添加一个字符串 -

using System;
class Program {
   static void Main() {
      string str = "World!";
      string modified_str = str.Insert(0, "Hello ");
      Console.WriteLine(modified_str);
   }
}

输出

以下是输出 -

Hello World!

示例 4:在字符串末尾插入

在此示例中,我们使用 Insert() 方法在当前字符串对象的末尾插入一个字符串 -

using System;
class Program {
   static void Main() {
      string str = "Hello";
      string to_be_insert = " tutorialspoint!";
      // 修改了字符串
      string modified_str = str.Insert(str.Length, to_be_insert);
      Console.WriteLine(modified_str);
   }
}

输出

以下是输出 -

Hello tutorialspoint!

csharp_strings.html