2018.8.30 转载请注明出处
定义一个字符串使用语句:
string str = "abc";
字符串可以自由拼接:
string str1 = "abc" + "def";
string str2 = string.Format("abc{0}","def");
上面的表达式中,str1和str2值均为"abcdef"
字符串常用属性有Length属性,可以得到字符串长度。
如上式中,str.Length 值为3。
string类中,有丰富的方法,几乎可以解决我们编程中的需求,例如ToUpper()方法可以将字符串内所有字符转成对应的大写字符,与之对应的方法ToLower,将其中所有字符转成对应的小写字符。
大量的方法可以在以下的链接中查看:
String 类 (System)msdn.microsoft.com
着重阐述以下几个很好用的字符串操作方法:
- Contains(String)判断字符串是否存在某指定字符串,返回值为bool值
- Replace(char,char)/Replace(string,string)将指定字符串中指定字符(串)替换成指定的新字符(串),返回值为修改后的字符串。
- Split(char[])基于数组中字符将指定字符串拆分成几个字符串数组,返回值为string[]形式。
Regex类方法
同样,Regex类中的方法可以在以下的链接中查看,里面的解释非常详细。
Regex 类 (System.Text.RegularExpressions)msdn.microsoft.com
Regex即正则表达式,在字符串匹配时非常有用,C#中正则表达式语法在下面链接中:
主要有两种使用方式,一种是实例化Regex对象,一种直接调用Regex类中方法,
常用的匹配方法有Match(),Matches(),IsMatch()等。
实例化Regex对象示例:
string pattern = @"\d+\.\d+\.\d+\.\d+";
string str = "1.1.1.1";
Regex regex = new Regex(pattern);
bool result1 = regex.IsMatch(str);
string result2 = regex.Match(str);
string[] result3 = regex.Matches(str)
直接调用Regex类方法示例:
string pattern = @"\d+\.\d+\.\d+\.\d+";
string str = "1.1.1.1";
bool result1 = Regex.IsMatch(str,pattern);
string result2 = Regex.Match(str,pattern);
string[] result3 = Regex.Matches(str,pattern)
IsMatch()方法用于判断是否匹配到正则表达式所匹配的字符串,返回值为一个bool值。
Match()方法用于找到第一个与正则表达式匹配的字符串,返回为所匹配到的字符串。
Matches()方法用于找到所有与正则表达式匹配的字符串,返回所匹配到的字符串组成的数组。