删除字符串:数组
String类提供了一个Remove方法,用于从一个字符串的指定位置开始,删除指定数量的字符,其语法格式以下:ide
public String Remove(int startIndex)spa
public String Remove(int startIndex,int count)索引
其中:rem
startIndex:用于指定开始删除的位置,索引从0开始。字符串
count:指定删除的字符数。string
参数count的值不能为0或是负数(startIndex参数也不能为负数),若是为负数,将会引起ArgumentOutOfRangeException异常(当参数值超出调用的方法所定义的容许取值范围时引起的异常);若是为0,则删除无心义,也就是没有进行删除。it
此方法有两种语法格式,第一种格式删除字符串中从指定位置开始到最后位置的全部字符。第二种格式从字符串中指定位置开始删除指定书目的字符。io
例如:建立一个控制台程序,声明一个string类型的变量str1,并初始化为:用一辈子下载你。而后使用remove方法的第一种语法格式删除从索引3后面的全部的字符。class
代码以下:
public static void Main(string[] args)
{
string str1="用一辈子下载你";
string str2=str1.Remove(3);
Console.WriteLine(str2);
Console.ReadKey();
}
例如:建立一个控制台应用程序,声明一个string类型的变量str1,并初始化为:我爱你花卉。而后使用Remove方法的第二种语法格式从索引位置3开始,删除两个字符。
public static void Main(string[] args)
{
string str1="我爱你花卉";
string str2=str1.Remove(3,2);
Console.WriteLine(str2);
Console.ReadKey();
}
复制字符串:
String类提供了Copy和CopyTo方法,用于将字符串或子字符串复制到另外一个字符串或Char类型的数组中。
一、Copy方法。
建立一个与指定的字符串具备相同值的字符串的新实例,其语法格式以下:
public static string Copy(string str)
str:是要复制的字符串。
返回值:与str具备相同值的字符串。
例如:建立一个控制台应用程序,声明一个string类型的变量str1,并初始化为:我爱你花卉。而后使用Copy方法复制字符串str1,并赋值给字符串str2。
string str1="我爱你花卉";
string str2;
str2=String.Copy(str1);
CopyTo方法
CopyTo方法的功能与Copy方法基本相同,可是CopyTo方法能够将字符串的某一部分复制到另外一个数组中。其语法格式以下:
public void CopyTo(int sourceIndex,char[] destination,int destinationIndex,int count)
sourceIndex 须要复制的字符的起始位置。
destination 目标字符数组
destinationindex 指定目标数组中的开始存放位置
count 指定要复制的字符个数
注意:当参数sourceIndex、ddestinationindex或count为负数,或者参数count大于从startIndex到此实例末尾的子字符串的长度,或者参数count大于从destinationIndex到destination末尾的子数组的长度时,则引起ArgumentOutOfRangeException异常。
例如:建立一个控制台应用程序,声明一个string类型的变量str1,并初始化为:用一辈子下载你。而后声明一个Char类型的数组str2,使用CopyTo方法将:一辈子下载 复制到数组str中。代码以下:
string str1="用一辈子下载你";
char[] str2=new char[100];
str1.CopyTo(1,str2,0,4);
替换字符串:
String类提供了一个Replace方法,用于将字符串中的某个字符或字符串替换成其余的字符或字符串。其语法格式以下:
public string Replace(char ochar,char nchar)
public string Replace(string ovalue,string nvalue)
ochar 待替换的字符
nchar 替换后的字符
ovalue 待替换的字符串
nvalue 替换后的字符串
第一种语法格式主要用于替换字符串中指定的字符,第二种语法格式主要用于替换字符串中指定的字符串。
例如:建立一个控制台应用程序,声明一个string类型的变量a,并初始化为:one world,one dream。而后使用Replace方法的第一种语法格式将字符串中的“,”替换为“*”。最后使用Replace方法的第二种语法格式将字符串中的“one word”替换成“One World”。
string a="one world,one dream";
string b=a.Replace(',','*');
string c=a.Replace("one world","One World");