在C#中, 删除() 方法是字符串方法。它用于从字符串的指定位置删除所有字符。如果未指定长度,则会删除指定位置后的所有字符。通过更改传递给该方法的参数数量,可以重载该方法。
null
语法:
public string Remove(int StartIndex) or public string Remove(int StartIndex, int count)
说明: 公共字符串删除(int StartIndex) )方法将采用一个作为起始索引的参数,或者我们可以说它将开始从当前字符串对象中删除字符的指定位置。此方法将继续删除字符,直到当前字符串对象结束。
公共字符串删除(int StartIndex,int count) 方法将采用两个参数,即第一个参数是指定字符串的起始位置,第二个参数是要删除的字符数。这两种方法的返回类型值均为 系统一串 .
例外情况: 可能有两种情况下会出现异常 ArgumentOutOfRange异常 可能发生的情况如下:
- StartIndex或(StartIndex+count)表示可能位于当前字符串对象之外的位置。
- StartIndex或count小于零。
以下是演示上述方法的程序:
- 例1: 演示 公共字符串删除(int StartIndex) 方法Remove方法将删除指定索引中的所有字符,直到字符串结束。
// C# program to illustrate the
// public string Remove(int StartIndex)
using
System;
class
Geeks {
// Main Method
public
static
void
Main()
{
// define string
String str =
"GeeksForGeeks"
;
Console.WriteLine(
"Given String : "
+ str);
// delete from index 5 to end of string
Console.WriteLine(
"New String1 : "
+ str.Remove(5));
// delete character from index 8 to end of string
Console.WriteLine(
"New String2 : "
+ str.Remove(8));
}
}
输出:Given String : GeeksForGeeks New String1 : Geeks New String2 : GeeksFor
- 例2: 演示 公共字符串删除(int StartIndex,int count) 方法此方法会将指定索引中的字符删除到字符串的指定索引+(count–1),其中count是要删除的字符数。
// C# program to illustrate the
// public string Remove(int StartIndex, int count)
using
System;
class
Geeks {
// Main Method
public
static
void
Main()
{
// original string
String str =
"GeeksForGeeks"
;
Console.WriteLine(
"Given String : "
+ str);
// delete the string from index 2 to length 4
Console.WriteLine(
"New String1 : "
+ str.Remove(2, 4));
// delete the string from index 5 to length 3
Console.WriteLine(
"New String2 : "
+ str.Remove(5, 3));
}
}
输出:Given String : GeeksForGeeks New String1 : GeorGeeks New String2 : GeeksGeeks
要记住的要点:
- 以上两种方法都不会修改当前字符串对象的值。相反,它们返回一个新的修改字符串。
- 如果StartIndex等于字符串的长度,且长度为零,则该方法不会从字符串中删除任何字符。
参考资料: https://msdn.microsoft.com/en-us/library/system.string.remove1
https://msdn.microsoft.com/en-us/library/system.string.remove2
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END