字符类型
C#语言中,使用char/Char类来定义字符,并且字符只能用单引号括起来。
语法:char c = 'a'; Char c = 'b';
转义字符:‘ \ ’,可以将字符转义成其他的含义。例如:\n代表换行,\t相当于Tab键......
字符串
声明字符串
- 法一:引用字符串常量进行初始化
string str = "abcd";
- 法二:利用字符数组进行初始化
构造方法:public string (char[] value)
char[] charArry={ 'a', 'b', 'c', 'd' };
string str = new string(charArry);
- 法三:提取字符数组中的一部分初始化
构造方法:public string(char[] value, int offset, int count)
char[] charArry={'t', 'i', 'm', 'e', 'i', 's', 't', 'r', 'e', 'a', 's', 'u', 'r', 'e' };
string str = new string(charArry, 2, 5);
字符串的拼接
使用“+”或“+=”运算符可以实现拼接多个字符串的功能。
字符串的比较
- 法一:使用compare方法
public static int Compare(string strA, string strB);
public static int Compare(string strA, string strB, bool ignoreCase);//第三个参数表示忽略大小写
相同返回值是0,小于返回值是负数,大于返回值是正数。
- 法二:使用CompareTo方法
public int CompareTo(Objiect value)
public int CompareTo(string value)
- 法三:使用Equals方法
public bool Equals(string value)
public static bool Equals(string a, string b)
字符串的格式化
语法:
public static string Format(string format, arg0)
public static string Format(string format, params Object[] args)
标准数值格式规范:
标准日期时间格式规范:
格式化的另一种方法:使用toString()方法
例:int money = 1000; Console.Writeline(money.ToString("C"));
DateTime time = DateTime.now; Console.Writeline(time.ToString("Y"));
字符串的截取
public string Substring(int startindex)
public string Substring(int startindex, int length)
字符串的分割
将字符串按照指定的符号分割成数组。
public string[] Split(char[] sseparator, int count)//指定分割符号,分割次数
例:
string str = "192.168.0.1";
string[] firstsep = string.Split(new char[]{'.'});//以.为分割界限,分成4部分
string[] firstsep = string.Split(new char[]{'.'}, 2);//以.为分割界限,分成2部分
字符串的插入
public string Insert(int startindex, string value)
字符串的删除
public string Remove(int startindex)
public string Remove(int startindex, int count)
字符串的复制
public static string Copy(string str)//全部复制
public void string CopyTo(int sourceindex, char[] destination, int destinationIndex, int count) //复制一部分
字符串的替换
public string Replace(char oldChar, char newChar) //复制单个字符
public string Replace(string oldValue, string newValue)//复制子字符串
PS:使用Replace方法时要注意大小写问题
可变字符串类