常用的字符串处理方法

来源:互联网 发布:java怎么固定gui位置 编辑:程序博客网 时间:2024/04/18 17:15

           字符串是程序中用得非常多的数据类型,是最常用的一个引用类型。String类属于System命名空间,是.NET Framework提供的专门处理字符串的类库。下面对常用的字符串处理方法做出说明:

常用字符串处理方法bool Equals(string str)与“==”作用相同,用于比较两个字符串是否相等,相等则返回true,否则返回falseToLower()返回字符串的小写形式ToUpper()返回字符串的大写形式Trim()去掉字符串两端的空格Substring(int a,int b)从字符串的指定位置a开始检索长度为b的子字符串int IndexOf(string str)获取指定的字符串str在当前字符串中的第一个匹配项的索引,有匹配项就返回索引,没有就返回-1int LastIndexOf(string str)获取指定的字符串str在当前字符串中的最后一个匹配项的索引,有匹配项就返回索引,没有就返回-1string[] Split(char separator)用指定的分隔符分割字符串,返回分割后的字符串组成的数组string Join(string sep,string[] str)字符串数组str中的每个字符用指定的分割符sep连接,返回连接后的字符串int Compare(string s1,string s2)比较两个字符串的大小,返回一个整数。如果s1小于s2,则返回值小于0;如果大于,则返回大于0;等于则返回0Replace(string oldV,string newV)用newV的值替换oldV的值




















接下来举例说明部分字符串的处理方法:

问题说明:

输入E-mail邮箱,获取邮箱用户名;

输入带空格的字符串,分割并连接;

输入大写英文字母,转化为小写。

代码实现:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Stringchuli{    class Program    {        static void Main(string[] args)        {            string strname;            string inputStr;            string[] splitString;            string joinString;            string strEnglish;            string email;            Console.WriteLine("请输入新的邮箱:");            email = Console.ReadLine().Trim();            Console.WriteLine("您的邮箱是{0}",email);            //抽取邮箱用户名            int intindex = email.IndexOf("@");            if (intindex > 0)            {                strname = email.Substring(0, intindex);                //输出邮箱用户名                Console.WriteLine("您的用户名是{0}", strname);            }            else            {                Console.WriteLine("你输入的格式错误!");            }            Console.WriteLine("请输入字符串,单词用空格分割:");            inputStr = Console.ReadLine();            Console.WriteLine("你输入的字符串是{0}",inputStr);            //用空格分割字符串            splitString = inputStr.Split(' ');            //输出分割后的字符串            Console.WriteLine("分割后的字符串是:");            foreach (string s in splitString)            {                Console.WriteLine(s);            }            //分割后的字符串用—连接            joinString = string.Join("-",splitString);            //输出连接后的字符串            Console.WriteLine("连接后的字符串是{0}",joinString);            Console.WriteLine("请输入大写英文字符串:");            strEnglish = Console.ReadLine();            Console.WriteLine("你输入的大写字符串是{0}",strEnglish);            //将输入的大写字符串转化为小写字符串            Console.WriteLine("转换为小写英文字符是{0}",strEnglish.ToLower());            Console.ReadLine();        }    }}
运行结果: