使用 string 定义的字符串,在定义好后,是无法修改的。如果要想改变,必须通过 tocharArray()函数将原来的字符串转化为字符(char)数组。然后再通过转换从而形成一个新的字符串。
字符串中常用的方法有:
下面我就举几个例子说明一下上面几个字符串方法的效果:1. 不区分大小写的比较
- #region 忽略大小写比较
- Console.WriteLine("请输入第一门课程:");
- string str3 = Console.ReadLine();
- Console.WriteLine("请输入第二门课程;");
- string str4 = Console.ReadLine();
- bool result = str3.Equals(str4, StringComparison.OrdinalIgnoreCase);
- //忽略大小写比较,其中,str4表示要比较的字符串,StringComparison.OrdinalIgnoreCase表示以忽略大小写的方式去比较。
- if (result)
- {
- Console.WriteLine("课程一样" + str3);
- }
- else
- {
- Console.WriteLine("课程不一样{0}_________{1}", str3, str4);
- }
- Console.ReadLine();
- #endregion
2. 移除字符串中不需要的字符。
- #region移除不需要的字符string str5 = "我 有一 个 朋 友,他------------叫小---------明"; //这是一个含有杂质的字符串,我想把其中的空格以及"-"去掉
- char[] chs1 = new char[] {'',
- ' - '
- }; //这里表示想要去除的杂质字符
- string[] result1 = str5.Split(chs1, StringSplitOptions.RemoveEmptyEntries);
- /*
- * 在上面一行代码中,因为是StringSplitOptions.RemoveEmptyEntries的原因,所以返回的值中没有空元素字符。如果要选择StringSplitOptions.none 则表示要返回
- * 带有空元素的字符。这两种方式的处理,在console.write()中无法看出区别,但是在console.writeLine()可以看出区别。
- */
- for (int i = 0; i < result1.Length; i++) {
- Console.Write(result1[i]);
- }
- Console.ReadLine();#endregion
3. 把字符串中某些字符或者字符串替换成其他的字符或者字符串
- #region把字符串中某些字符或者字符串替换成其他的字符或者字符串。
- string str = "老杨很邪恶";
- str = str.Replace('很', '不');
- Console.WriteLine(str);
- Console.ReadLine();
- str = str.Replace("老杨", "老苏");
- Console.WriteLine(str);
- Console.ReadLine();
- #endregion
4. 判断字符串中是否包含要查的字符串
- #region 判断字符串中是否包含要查的字符串。
- string str = "小杨很邪恶";
- bool result = str.Contains("小杨");
- if (result)
- {
- Console.WriteLine(result);
- Console.ReadLine();
- }
- #endregion
5. 找到某个字符的索引在截取
- #region找到某个字符的索引在截取string str = "小杨很邪恶";
- str = str.Substring(3); //截取字符,在字符下标为3的地方开始截取,保留后面的东西。,但是下标不能超过字符串长度。
- Console.WriteLine(str);
- Console.ReadLine();
- str = "小杨很邪恶";
- str = str.Substring(3, 2); //表示从第三个字符开始,然后截取三个字符。两个数值的下标均不能超过字符长度
- Console.WriteLine(str);
- Console.ReadLine();
- /***********************************************************************************************************/
- //截取路径中H:\学习资料\提高班\cs学习\传智播客基础实训3\20121102C#基础\视频\22移除字符串的方法.avi中的22移除字符串的方法.avi
- string path = @"H:\学习资料\提高班\cs学习\传智播客基础实训3\20121102C#基础\视频\22移除字符串的方法.avi"; //这里要使用@,
- //方法一
- path = path.Substring(path.Length - 14);
- Console.WriteLine(path);
- Console.ReadLine();
- //方法二:
- char[] chs = new char[1] {'\\'
- };
- string[] path1 = path.Split(chs);
- Console.WriteLine(path1[path1.Length - 1]);
- Console.ReadLine();
- #endregion
6. 判断字符串是否以某个字符串开始或者结束的
- #region 判断字符串是否以某个字符串开始或者结束的。
- string str = "小杨很纯洁";
- bool result = str.StartsWith("小杨");
- if (result)
- {
- Console.WriteLine("是这个字符串开始的");
- Console.ReadLine();
- }
- result = str.EndsWith("纯洁");
- if (result)
- {
- Console.WriteLine("是这个字符串结束的");
- Console.ReadLine();
- }
- #endregion
来源: http://www.bubuko.com/infodetail-2437570.html