C# 字符串类型介绍与操作

时间:2023-03-10 05:44:06
C# 字符串类型介绍与操作

一、关于字符串操作的方法

System.String类提供了很多工具方法,包括返回字符数据长度,查找当前字符串中的子字符串和转换大小写等方法。

C# 字符串类型介绍与操作

在String类中常用的比较字符串的方法主要有Compare()和CompareTo()和Equals()以及CompareOrdinal(),下面将分类解析:

1、Compare()和CompareTo()

(1)、Compare()是String类的静态方法,用于全面比较两个字符串对象,包括10种重载方法。

(2)、ConpareTo()将当前字符串对象与另一个对象做比较,其作用与Compare类似,返回值也相同。

他们之间的区别是Compare()是String类的静态方法,CompareTo()不是静态方法,可以通过String对象实例来调用;CompareTo()方法没有重载形式,只能按照字符串大小来比较两个字符串对象;

//Compare
string test = "";
string test1="";
int result=string.Compare(test, test1);
Console.WriteLine("Is test bigger than test1?{0}", result);//输出:-1 //CompareTo
int result1 = test.CompareTo(test1);
Console.WriteLine("Is test bigger than test1?{0}", result1);//输出:-1

上面的代码说明了Compare()和CompareTo()的区别

2、Compare()重载方法详解

(1)String.Compare(string strA,int indexA,string strB,int indexB,int length)

参数说明

strA   ---要比较的第一个字符串对象

indexA   ---要比较的第一个字符串对象中需要截取的子字符串的       开始的索引

strB   ---要比较的第二个字符串对象

indexB   ---要比较的第二个字符串对象中需要截取的子字符串的       开始的索引

length   ---需要截取的子字符串的长度    注意:这个值不能小于0,但是可以大于字符串对象的长度(大于字符串对象的长度,就取字符串对象的长度)

string str1 = "machide";
string str2 = "device";
string str;
int result;
Console.WriteLine();
Console.WriteLine("str1={0},str2={1}", str1, str2);
result=string.Compare(str1,,str2,,);//比较
str = result < ? "less than" : result == ? "equal to" : "greater than";//equal to
Console.WriteLine("substring {0} in {1} is", str1.Substring(, ), str1);
Console.WriteLine("{0}", str);
Console.WriteLine("substring {0} in {1}", str2.Substring(, ), str2);

(2)String.Compare(string strA,int indexA,string strB,int indexB,int length, Boolean bool)

参数说明

strA      ---要比较的第一个字符串对象

indexA  ---要比较的第一个字符串对象中需要截取的子字符串的       开始的索引

strB      ---要比较的第二个字符串对象

indexB  ---要比较的第二个字符串对象中需要截取的子字符串的       开始的索引

length   ---需要截取的子字符串的长度    注意:这个值不能小于0,但是可以大于字符串对象的长度(大于字符串对象的长度,就取字符串对象的长度)

bool      ---需要比较的子字符串是否需要区分大小写

            string str1 = "MACHIDE";
string str2 = "device";
string str,str3;
int result,result1;
Console.WriteLine("str1={0},str2={1}", str1, str2);
result=string.Compare(str1,,str2,,,false); //比较两个子字符串 区分大小写
str = result < ? "less than" : result == ? "equal to" : "greater than"; //输出:greater than
Console.WriteLine("substring {0} in {1} is", str1.Substring(, ), str1);
Console.WriteLine("{0}", str);//输出:greater than
Console.WriteLine("substring {0} in {1}", str2.Substring(, ), str2);
Console.WriteLine(); result1 = string.Compare(str1, , str2, ,, true);//设置true 比较两个子字符串 不区分大小写
str3 = result1 < ? "less than" : result1 == ? "equal to" : "greater than"; //输出:equal to
Console.WriteLine("substring {0} in {1} is", str1.Substring(, ), str1);
Console.WriteLine("{0}", str3);//输出:equal to
Console.WriteLine("substring {0} in {1}", str2.Substring(, ), str2);

(3)String.Compare 方法 (string strA,int indexA,string strB,int indexB,int length, Boolean bool, CultureInfo cultureinfo)

strA      ---要比较的第一个字符串对象

indexA  ---要比较的第一个字符串对象中需要截取的子字符串的       开始的索引

strB      ---要比较的第二个字符串对象

indexB  ---要比较的第二个字符串对象中需要截取的子字符串的       开始的索引

length   ---需要截取的子字符串的长度    注意:这个值不能小于0,但是可以大于字符串对象的长度(大于字符串对象的长度,就取字符串对象的长度)

bool      ---需要比较的子字符串是否需要区分大小写

cultureinfo    ---程序的运行地域信息     详见http://blog.csdn.net/xuwei_xuwei/article/details/32717259

            String str1 = "MACHINE";
String str2 = "machine";
String str;
int result; Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
Console.WriteLine("Ignore case, Turkish culture:");
result = String.Compare(str1, , str2, , , true, new CultureInfo("tr-TR"));//改变地域(相当于这个程序可能是给德国用户用的,这个时候就要改变)
str = ((result < ) ? "less than" : ((result > ) ? "greater than" : "equal to"));//less than 说明在"tr-TR"这个地域下in比in小
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(, ), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(, ), str2); Console.WriteLine();
Console.WriteLine("Ignore case, invariant culture:");
result = String.Compare(str1, , str2, , , true, CultureInfo.InvariantCulture);//程序不会因为输出客户端的地域改变而造成不同的输出
str = ((result < ) ? "less than" : ((result > ) ? "greater than" : "equal to"));//equal to 默认地域下 in和in一样大
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(, ), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(, ), str2);

(4)String.Compare 方法 (string strA,int indexA,string strB,int indexB,int length, Boolean bool, CultureInfo cultureinfo,CompareOptions CompareOptions.IgnoreCase)

strA      ---要比较的第一个字符串对象

indexA  ---要比较的第一个字符串对象中需要截取的子字符串的       开始的索引

strB      ---要比较的第二个字符串对象

indexB  ---要比较的第二个字符串对象中需要截取的子字符串的       开始的索引

length   ---需要截取的子字符串的长度    注意:这个值不能小于0,但是可以大于字符串对象的长度(大于字符串对象的长度,就取字符串对象的长度)

cultureinfo    ---程序的运行地域信息     详见http://blog.csdn.net/xuwei_xuwei/article/details/32717259

CompareOptions.IgnoreCase      ---设置比较判断的子字符串不区分大小写

string name1 = "Jack Smith";
string name2 = "John Doe";
int result; // Get position of space character.
int index1 = name1.IndexOf(" ");
index1 = index1 < ? : index1++;
int index2 = name2.IndexOf(" ");
index2 = index2 < ? : index2++;
int length=Math.Max(name1.Length,name2.Length);
CultureInfo cultureinfo=new CultureInfo("en-US");//客户端所在的地域
CompareOptions ignoreCase = CompareOptions.IgnoreCase;//忽略要比较大小的两个子字符串的大小写
result = string.Compare(name1, index1, name2, index2, length, cultureinfo, ignoreCase);
string str = result < ? "less than" : result == ? "equal to" : "greater than";
Console.WriteLine("Jack Smith's Family Name is {0}", name1.Substring(index1));
Console.WriteLine("{0}", str);//输出:greater than
Console.WriteLine("John Doe's Family Name {0}", name2.Substring(index2));

(5)String.Compare 方法 (string strA,int indexA,string strB,int indexB,int length, StringComparison comparson)

strA      ---要比较的第一个字符串对象

indexA  ---要比较的第一个字符串对象中需要截取的子字符串的       开始的索引

strB      ---要比较的第二个字符串对象

indexB  ---要比较的第二个字符串对象中需要截取的子字符串的       开始的索引

length   ---需要截取的子字符串的长度    注意:这个值不能小于0,但是可以大于字符串对象的长度(大于字符串对象的长度,就取字符串对象的长度)

comparson   ---StringComparson枚举,下面是其成员

成员名称 说明
  CurrentCulture

使用区分区域性的排序规则和当前区域性比较字符串。

  CurrentCultureIgnoreCase

通过使用区分区域性的排序规则、当前区域性,并忽略所比较的字符串的大小写,来比较字符串。

  InvariantCulture

使用区分区域性的排序规则和固定区域性比较字符串。

  InvariantCultureIgnoreCase

通过使用区分区域性的排序规则、固定区域性,并忽略所比较的字符串的大小写,来比较字符串。

  Ordinal

使用序号(二进制)排序规则比较字符串。

  OrdinalIgnoreCase

通过使用序号(二进制)区分区域性的排序规则并忽略所比较的字符串的大小写,来比较字符串。

            String str1 = "machVIne";
String str2 = "device";
String str;
int result;
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
StringComparison comparison = StringComparison.CurrentCultureIgnoreCase;//通过使用区分区域性的排序规则、当前区域性,并忽略所比较的字符串的大小写,来比较字符串。
result = String.Compare(str1, , str2, , , comparison);
str = ((result < ) ? "less than" : ((result > ) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(, ), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(, ), str2);

3、Substring()方法详解

(1)string.Subtring(int startIndex )

index   ---此实例中子字符串的起始字符位置(从零开始)。

注意:startIndex 小于零或大于此实例的长度,会报异常;

            string[] info = { "name:张三", "age:23", "sex:男" };
Console.WriteLine("The initial values in the array are:");
foreach (string s in info) {
Console.WriteLine(" {0}", s);
}
Console.WriteLine("I want to retrieve the value information. That is");
foreach (string s in info) {
int index = s.IndexOf(":");
Console.WriteLine(" {0}", s.Substring(index + ));//当Substring()只给它一个int参数时,他默认截取从这个int参数开始到这个字符串的最后的这个子字符串
}

(2)string.Subtring(int startIndex,int count)

index   ---截取的开始的索引(从零开始)。

count   ---截取的长度

            string str="Hello World";
Console.WriteLine("{0}", str.Substring(, ));//输出:H 注意不包含索引为1的那个字母

4、string.Contains()方法详解

作用:检测对象实例中是否包含与传入字符串参数相同的值      非静态方法

返回值:true/false

string.Contains(string value)

value    ---需要检查的字符串参数

string str1 = "hello world";
Console.WriteLine("str1 Contains hello is {0}", str1.Contains("hello"));//输出:str1 Contains hello is True

5、string.Equals()方法详解

(1)equals(object ob)      非静态方法

作用:检测对象实例是否与传入的object参数相同      非静态方法

ob   要与检测对象实例进行比较的对象

object ob = ;
Console.WriteLine("ob is equal to 111? {0}", ob.Equals());//输出:ob is equal to 111? True
Console.WriteLine("ob is equal to 111? {0}", ob.Equals(""));//输出:ob is equal to 111? False

(2)equals(string str)      非静态方法

作用:检测对象实例是否与传入的string字符串参数相同      非静态方法

str   要与检测对象实例进行比较的字符串

string str = "hello";
Console.WriteLine("ob is equal to hello? {0}", str.Equals("hello"));//输出:ob is equal to hello? True

(3)string.equals(string str1,string str2)   静态方法

作用:判断传入的两个字符串对象是否相同

str1  字符串对象一

str2  字符串对象二

string str1 = "hello";
string str2 = "hello";
Console.WriteLine("str1 is equal to str2? {0}", string.Equals(str1, str2));//输出:str1 is equal to str2? True

(4)string.equals(string str1,string str2,StringComparison sc)   静态方法

作用:在StringComparison枚举指定的情况下,判断传入的两个字符串对象是否相同

str1  字符串对象一

str2  字符串对象二

sc     StringComparson枚举,下面是其成员

成员名称 说明
  CurrentCulture

使用区分区域性的排序规则和当前区域性比较字符串。

  CurrentCultureIgnoreCase

通过使用区分区域性的排序规则、当前区域性,并忽略所比较的字符串的大小写,来比较字符串。

  InvariantCulture

使用区分区域性的排序规则和固定区域性比较字符串。

  InvariantCultureIgnoreCase

通过使用区分区域性的排序规则、固定区域性,并忽略所比较的字符串的大小写,来比较字符串。

  Ordinal

使用序号(二进制)排序规则比较字符串。

  OrdinalIgnoreCase

通过使用序号(二进制)区分区域性的排序规则并忽略所比较的字符串的大小写,来比较字符串。

string str1 = "hello";
string str2 = "HELLO";
StringComparison sc = StringComparison.CurrentCultureIgnoreCase;//忽略判断对象的大小写问题
Console.WriteLine("str1 is equal to str2? {0}", string.Equals(str1, str2, sc));//输出:str1 is equal to str2? True

(5)equals(string str,StringComparison sc)   非静态方法

作用:判断检测对象实例在StringComparison枚举指定的规则下,是否与str对象相同

str   需要判断字符串对象

sc   与上同

string str1 = "hello";
string str2 = "HELLO";
StringComparison sc = StringComparison.CurrentCultureIgnoreCase;//忽略判断对象的大小写问题
Console.WriteLine("str1 is equal to str2? {0}", str1.Equals(str2,sc));//输出:str1 is equal to str2? True

6、Insert(int startIndex,string value)方法详解    非静态

作用:从指定索引(startIndex)处,插入传入的字符串(value)

startIndex   ---字符串从startIndex位置处开始插入

value          ---要插入的内容

            string animal1 = "fox";
string animal2 = "dog";
string strTarget = string.Format("The {0} jumped over {1}", animal1, animal2);
Console.WriteLine("The original string is:{0}{1}{0}", Environment.NewLine, strTarget);
Console.WriteLine("Enter an adjective(or group of adjectives)"
+ "to describe the {0}", animal1);
string adj1 = Console.ReadLine();
Console.WriteLine("Enter an adjective(or group of adjectives)"
+ "to describe the {0}", animal2);
string adj2 = Console.ReadLine();
adj1 = adj1.Trim() + " ";
adj2 = adj2.Trim() + " ";
strTarget = strTarget.Insert(strTarget.IndexOf(animal1), adj1);
strTarget = strTarget.Insert(strTarget.IndexOf(animal2), adj2);
Console.WriteLine("The final string is {0}", strTarget);

7、PadLeft()方法详解

(1)PadLeft(int length)

作用:返回一个新字符串,该字符串通过在此实例中的字符左侧填充空格来达到指定的总长度,从而实现右对齐。

length   ---向左边填充空格来达到指定的总长度(length)

string str = "day day up";
Console.WriteLine("{0}", str.PadLeft());//输出: day day up这个字符串长度为20,左边填充的都是空格

(2)PadLeft(int length,Char ch)

作用:返回一个新字符串,该字符串通过在此实例中的字符左侧填充指定的传入字符(ch)来达到指定的总长度,从而实现右对齐

length   ---总长度

ch         ---用于在左边填充的字符

string str = "day day up";
Console.WriteLine("{0}", str.PadLeft(, '-'));//输出:----------day day up这个字符串长度为20,左边填充的都是'-'符

8、PadRight()方法详解

与PagLeft()相反

9、remove()方法详解

(1)remove(int startindex)

作用:删除字符串对象实例从startindex位置开始之后的所有的字符

startindex   ---删除开始的位置索引

string str = "abc---def";
Console.WriteLine("1){0}", str.Remove());//输出:1)abc

(2)remove(int startindex,int count)

作用:删除字符串对象实例从startindex开始,并删除count个字符

startindex   ---删除开始的位置索引

count          ---要删除的字符个数

string str = "abc---def";
Console.WriteLine("1){0}", str.Remove(, ));//输出:1)abcdef

10、Replace()方法详解

(1)、Replace(Char ch1,Char ch2)

作用:将字符串对象实例中的ch1字符替换成ch2字符

ch1          ---老字符(字符串对象实例中的字符)

ch2          ---要替换的新字符

string s = new String('a', );
Console.WriteLine("{0}", s);
s = s.Replace('a', 'b').Replace('b', 'c').Replace('c', 'd');
Console.WriteLine("The final s is {0}", s);

(2)、Replace(string oldValue,string newValue)

作用:将字符串对象实例中的oldValue字符串对象替换成newValue字符串对象实例

oldValue    ---要替换的字符串对象(字符串对象实例中的字符)

newValue   ---替换的新字符串对象

string s = new String('a', );
Console.WriteLine("{0}", s);
s = s.Replace("aa", "bb");
Console.WriteLine("The final s is {0}", s);//输出:The final s is bba