C# 字符串 - Remove() 方法

C# 字符串 Remove() 方法用于从字符串中删除指定字符并返回一个新字符串。

要删除的字符取决于起始索引和计数。起始索引表示字符串中要开始删除字符的位置,而计数指定要删除的字符总数。

语法

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

public string Remove (int startIndex, int count);

参数

此方法接受以下参数 -

  • startIndex:表示要从中删除的位置。
  • count:表示要从字符串中删除的字符数。

返回值

此方法返回一个新字符串。除了已删除的字符外,新字符串与当前字符串相同。

示例 1:从起始索引到末尾删除字符

以下是 Remove() 方法的基本示例,用于从字符串的起始索引到末尾删除字符 -

    
using System;
class Program {
   static void Main() {
      string original = "tutorialspoint, India";
      string result = original.Remove(5);
      Console.WriteLine(result);
   }
}

输出

以下是输出 -

tutor

示例 2:删除特定数量的字符

我们来看另一个示例。这里,我们使用 Remove() 方法从字符串的起始索引处删除特定数量的字符 -

using System;
class Program {
   static void Main() {
      string original = "tutorialspoint, India";
      string result = original.Remove(14, 7);
      Console.WriteLine(result);
   }
}

输出

以下是输出 -

tutorialspoint

示例 3:尝试删除超出字符串长度的部分

在此示例中,我们使用 Remove() 方法从字符串中删除指定数量的字符。如果指定的长度超出了字符串的实际长度,则会收到 ArgumentOutOfRangeException.exception -

using System;
class Program {
  static void Main() {
    string original = "Hello, tpians!";
    try {
      string result = original.Remove(7, 20);
      Console.WriteLine(result);
    } catch (ArgumentOutOfRangeException ex) {
      Console.WriteLine("Error: " + ex.Message);
    }
  }
}

输出

以下是输出 -

Error: Index and count must refer to a location within the string.
Parameter name: count

示例 4:从电子邮件地址中删除域名

在此示例中,我们使用 Remove() 方法从电子邮件地址中删除域名部分(@ 符号后的每个字符)-

using System;
class Program { 
   static void Main() {
      string email = "amangupta123@gmail.com";
      
      // 查找 '@' 的索引
      int atIndex = email.IndexOf('@');

      // 如果发现"@",则删除域部分
      string username = atIndex >= 0 ? email.Remove(atIndex) : email;

      Console.WriteLine("Original Email: " + email);
      Console.WriteLine("Username Only: " + username); 
   }
}

输出

以下是输出 -

Original Email: amangupta123@gmail.com
Username Only: amangupta123

csharp_strings.html