標籤:
一、字串
c#中提供了一系列關於string類型的值的操作,便於我們對string進行各種類型的操作,例如比較,轉化成字串等等
eg:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;namespace stringand{ class Program { static void Main(string[] args) { int a = 554; string stringa = a.ToString();//把a的內容以字串形式輸出 string b = "qwer"; string c = "asdf"; Console.WriteLine(b.CompareTo(c));//比較string b和c的大小,若為正數,則前者大 //若為0,則兩者相等,若為負數,則後者大,此處返回1 Console.WriteLine(string.Compare(b,c));// 返回1 } }}
另外,附上一些string類包含的方法
二、Regex
C#中為Regex的使用提供了非常強大的功能,這就是Regex類。這個包包含於System.Text.RegularExpressions命名空間下面。
eg:
Regex regex = new Regex(@"\d");// \d為匹配數字
regex.IsMatch("abc"); //傳回值為false,字串中未包含數字
regex.IsMatch("abc3abc"); //傳回值為true,因為字串中包含了數字
regex.Matches("abc123abc").Count;//返回3,因為匹配到3個數字
regex.Match("abc123abc").Value;// 返回為1,因為是匹配到第一個數位值
下面是在vs中的一些執行個體:
string s1 = "One,Two,Three Liberty Associates, Inc."; Regex theRegex = new Regex(" |, |,"); StringBuilder sBuilder = new StringBuilder(); int id = 1; foreach (string subString in theRegex.Split(s1)) { sBuilder.AppendFormat("{0}: {1}\n", id++, subString); } Console.WriteLine("{0}", sBuilder);
string string1 = "This is a test string"; // find any nonwhitespace followed by whitespa Regex theReg = new Regex(@"(\S+)\s"); // get the collection of matches MatchCollection theMatches = theReg.Matches(string1); // iterate through the collection foreach (Match theMatch in theMatches) { Console.WriteLine("theMatch.Length: {0}", theMatch.Length); if (theMatch.Length != 0) { Console.WriteLine("theMatch: {0}", theMatch.ToString( )); } }
結果為:
string string2 = "04:03:27 127.0.0.0 LibertyAssociates.com " + "04:03:28 127.0.0.0 foo.com " + "04:03:29 127.0.0.0 bar.com "; Regex theReg2 = new Regex(@"(?<time>(\d|\:)+)\s" +@"(?<ip>(\d|\.)+)\s" + @"(?<site>\S+)");// \S :與任何非空白的字元匹配。 MatchCollection theMatches2 = theReg2.Matches(string2); foreach (Match theMatch in theMatches2) {// iterate through the collection if (theMatch.Length != 0) { Console.WriteLine("\ntheMatch: {0}", theMatch.ToString()); Console.WriteLine("time:{0}",theMatch.Groups["time"]); Console.WriteLine("ip: {0}", theMatch.Groups["ip"]); Console.WriteLine("site: {0}", theMatch.Groups["site"]); } }
結果為:
c#學習筆記之字串和Regex