在文字的处理方面,大多都是通过字符和字符串的操作来实现。在C#中,主要用Char类、String类、StringBuild类来实现。在学习过程中,发现对于这类的处理,在调用上主要有两个使用方式,一种是类的static函数调用,另一种是用例的方法调用。
比如:
static方法的调用:
Char.IsLetter('a');//判断指定的字符是否是字母类别。
用例的调用
string MyStr = "my value string";
MyStr.CompareTo("another string");
简单来说,就是类的静态方法属于类自身,在调用时,是类方法调用;而另一种就是,类实例调用方法,在调用时,该方法是属于这个实例的。
正常来说,相同功能的方法都会有这两种形式可调用的实现,如果在实现使用中,不确定该使用哪种调用方式,可以从该方法的定义来确认调用形式。
属于类的静态方法,在定义时,有一个static关键字,而用例的方法则没有。
如比较方法:
public bool CompareTo(string value);
public static bool Compare(string a, string b);
//在调用使用时,形式如下,
string stra = "string a";
string strb = "string b";
stra.CompareTo(strb);
String.Compare(stra, strb);
在学习过程中,熟悉各个基本的String类的方法是必须,对于不清楚的方法,在编程过程中,如果编程工具是VS,也可以直接通过F12,查看该方法的使用简介和参数类型来大概定位可以使用的方式。
基于此,这里简单记录下常用的String类的方法。
(1)比较字符串
public Int Compare(string strA, string strB);
public Int Compare(string strA, string strB, bool ignorCase);
ignorCase为真时,表示比较过程中忽略大小写。
String.Compare(myStrA, myStrB, true);
public Int CompareTo(string strB);
myStrA.CompareTo(myStrB);
public bool Equals(string value);
public static bool Equals(string a, string b);
myStrA.Equals(myStrB);
String.Equals(myStrA, myStrB);
(2)格式化字符串
Public static string Format(string format, object obj);
格式项format的语法是{索引[,对齐方式][:格式字符串]}。
DateTime dt = DateTime.Now;//获取当前时间
String strB = String.Format("{0:D}", dt);//格式化成短日期格式(YYYY年MM月dd日)
(3)截取字符串
public string Substring(int startIndex, int length);
(4)分割字符串
public string[ ] Split(char[ ] separator);
string myStr = "this*is^my string";
char[] separator = {'^', '#', '*'};
string[] splitstring = string[100];
splitstring = myStr.Split(separator);
for(int i=0; i < splitstring.Length; i++)
Console.WriteLine("item{0}:{1}", i, splitstring[i]);
(5)插入字符串
public string Insert(int startIndex, string value);
(6)填充字符串
有左填充和右填充两种。
public string PadLeft(int totalWidth, char paddingChar);
public string PadRight(int totalWidth, char paddingChar);
(7)删除字符串
public string Remove(int startIndex);
public string Remove(int startIndex, int count);
(8)复制字符串
public static string Copy(string str);
public void CopyTo(int sourceIndex, char[ ] destination, int destinationIndex, int count);
(9)替换字符串
public string Replace(char OChar, char NChar);
public string Replace(string OValue, string NValue);
与String类相比,如果是需要经常修改字符串的操作,应该定义为StringBuilder类实例,是比较合理的选择。
StringBuilder类的构造方法有多种,当定义了一个类实例后,后续对实例的修改可以直接通过调用实例方法来实现。
StringBuilder myValue = new StringBuilder("this is my string");
myValue.Append(" and that is yours");
//则myValue的值为this is my string and that is yours.
常见的方法有Append、AppendFormat、Insert、Remove、Replace等