跳到主要内容

C# String Remove() 字符串移除方法

String 类的 Remove() 方法用于移除字符串中指定数量的字符。

示例

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str = "Ice cream";

// 从索引 2 开始移除字符
string result = str.Remove(2);
Console.WriteLine(result);

Console.ReadLine();
}
}
}

// 输出:Ic

Remove() 方法语法

字符串 Remove() 方法的语法是:

Remove(int startIndex, int count)

这里,Remove()String 类的一个方法。

Remove() 方法参数

Remove() 方法接受以下参数:

  • startIndex - 开始删除字符的索引
  • count (可选) - 要删除的字符数量

Remove() 方法返回值

Remove() 方法返回:

  • 移除字符后的字符串

示例 1:C# 字符串 Remove()

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str = "Chocolate";

// 从索引 5 开始移除字符
string result = str.Remove(5);
Console.WriteLine(result);

Console.ReadLine();
}
}
}

输出

Choco

这里,

  • str.Remove(5) - 移除了从索引 5 开始的所有字符

示例 2:C# 字符串 Remove() 指定 Count

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str = "Chocolate";

// 从索引 5 开始移除 2 个字符
string result = str.Remove(5, 2);
Console.WriteLine(result);

Console.ReadLine();
}
}
}

输出

Chocote

这里,

  • str.Remove(5, 2) - 移除了索引 5 处的 2 个字符('l''a'