String 类
- string可以看做是char的只读数组。char c = s[1];。例子:遍历输出string中的每个元素。
- C#中字符串有一个重要的特性:不可变性,字符串一旦声明就不再可以改变。所以只能通过索引来读取指定位置的char,不能对指定位置的char进行修改。如果要对char进行修改,那么就必须创建一个新的字符串,用s. ToCharArray()方法得到字符串的char数组,对数组进行修改后,调用new string(char[])这个构造函数(暂时不用细研究)来创建char数组的字符串。一旦字符串被创建,那么char数组的修改也不会造成字符串的变化。
常见疑问:谁说字符串不可变?string s = "abc";s="123",s这不是变了吗
要区分变量名和变量指向的值的区别。程序中可以有很多字符串,然后由字符串变量指向他们,变量可以指向其他的字符串,但是字符串本身没有变化。字符串不可变性指的是内存中的字符串不可变,而不是变量不变。
string s10 = s1;//s10指向s1指向的字符串,而不是s10指向s1,哪怕s1以后指向了其他内存,那么s10还是指向"hello"
例子:将字符串中的l替换为i
1 string s = "hell world!";//字符数组 只读的 不能对其 进行赋值 2 char[] chars = s.ToCharArray();//得到一个字符数组 3 chars[1]='i';//修改字符数组的值 4 s=new string(chars);//生成一个新的字符串 5 Console.WriteLine(s); 6 for (int i = 0; i < s.Length; i++) 7 { 8 Console.WriteLine(s[i]); 9 } 10 Console.ReadKey();
string类常用方法
l ToLower():得到字符串的小写形式。
l 注意字符串是不可变的,所以这些函数都不会直接改变字符串的内容,而是把修改后的字符串的值通过函数返回值的形式返回。s.ToLower()与s=s.ToLower()
l ToUpper():得到字符串的大写形式; Trim()去掉字符串两端的空白。
scoreA.ToUpper() == scoreB.ToUpper()
l s1.Equals(s2, StringComparison.OrdinalIgnoreCase),两个字符串进行比较不区分大小写的比较。
string.Equals(scoreA, scoreB, StringComparison.OrdinalIgnoreCase); //OrdinalIgnoreCase忽略大小写 并且可以防止字符串为空无法显示结果
l Replace 字符串替换
string Replace(string oldValue, string newValue)将字符串中的出现oldValue的地方替换为newValue。
l substring 取子字符串
string str = "hello,world!"; string result = str.Substring(6, 2);//从下标为6的开始截取2位 第2个参数是长度 Console.WriteLine(result); Console.ReadKey();
bool Contains(string value) 判断字符串中是否含有子串value
string[] words= {"自由","和谐","xxoo"}; Console.WriteLine("输入您想说的一句话?"); string cen=Console.ReadLine(); int i; startIndex for(i=0;i<words.Length;i++) { if(cen.Contains(words[i]))//如果这句话中有第i个元素 { cen = cen.Replace(words[i], "****"); //break; } } // if (i < words.Length) { //含有敏感词语 Console.WriteLine("你输入的内容中有非法字符,不能显示!"); } else { //没有 Console.WriteLine("你刚输入的{0},已发表成功!",cen); }
bool StartsWith(string value)判断字符串是否以子串value开始;
bool EndsWith (string value)判断字符串是否以子串value结束;
int IndexOf(string value):取子串value第一次出现的位置。
string str = "Hello,World!"; Console.WriteLine(str.IndexOf("o", 5)); Console.ReadKey();
Int IndexOf(string value,int startIndex)
string Substring(int startIndex, int length),取从位置startIndex开始长度为length的子字符串,如果子字符串的长度不足length则报错。
string Substring(int startIndex),取从位置startIndex开始一直到最后的子字符串;
字符串的分割 Split
string[] Split(params char[] separator):将字符串按照指定的分割符分割为字符串数组;
string[] Split(char[] separator, StringSplitOptions options)将字符串按照指定的char分割符分割为字符串数组( options 取RemoveEmptyEntries的时候移除结果中的空白字符串);
string str = "How are you? Find,Thank you!"; //string[] words = str.Split(' ', '?', '!', ','); char[] removeChar = { ' ', '?', '!', ',' }; string[] words = str.Split(removeChar, StringSplitOptions.RemoveEmptyEntries); //string[] words=str.Split(' '); Console.WriteLine("上句话中共有{0}个单词", words.Length); Console.WriteLine("这几个单词分别为:"); for (int i = 0; i < words.Length; i++) { Console.WriteLine(words[i]); } Console.ReadKey();