Appearance
字符与字符串
字符
csharp
// 省略导入文件
namespace CharString{
class Program{
static void Main(string[] args){
char char1 = 'a';
string string1 = "hello\n world";
// \n是转义字符,代表换行。还有其他的转义字符,特征是反斜杠+单个小写字母或符号
string string2 = @"Nice to "" meet you!"
// 使用@作为字符串的开头可以将内容原封不动地输出,即原本会转义的字符都不会转义。中间的双引号会被替换为一个双引号
// 使用@开头还可以将一行字符串分两行书写,如下所示
string string3 = @"hello
world";
Console.WriteLine(string2);
Console.ReadKey();
}
}
}
一长串的字符可以组成字符串。但是用字符组串太过低效。我们有另一种选择:字符串。
字符串
在前面几节中也创建过字符串。在这里先复习一下
csharp
static void Main(string[] args){
string str = "Hello World!";
Console.Write(str);
Console.ReadKey();
}
字符串的属性
字符串有两个属性:chars, length
其中,chars的定义如下
public char this[int index] { get; }
this指代的是字符串,其实也就是可以用下标访问字符串的意思。
length就直观一些
csharp
static void Main(string[] args){
string str = "Hello World!";
Console.WriteLine(str[2]); // 字符串可以用下标访问
Console.Write(str.Length);
Console.ReadKey();
}
字符串的方法
方法 | 描述 |
---|---|
Concat(string str1, string str2) | 连接字符串 |
Compare(string str1, string str2, bool ignoreCase) | 比较字符串。第三个参数用于决定是否忽略大小写 |
Contains(string value) | 字符串中是否有value出现 |
Copy(string str) | 复制字符串 |
StartsWith(string str) | 字符串是否以value开头 |
EndsWith(string value) | 字符串是否以value结尾 |
IndexOf(string value) | value在字符串中第一次出现的位置。没出现过返回-1。注意这个函数有重载 |
LastIndexOf(string value) | value在字符串中最后一次出现的位置。没出现过返回-1。注意这个函数有重载 |
Join(string separator, string[] value) | 指定分隔符,将字符串数组value中的所有字符串相连 |
Replace(string oldValue, string newValue) | 新字符串替换字符串。有重载 |
Split(params char[] separator) | 以参数数组为分隔符分割字符串。返回的是字符串数组。 |
ToLower() | 转成小写 |
ToUpper() | 转成大写 |
Trim() | 移除字符串头尾的空白字符 |
SubString(int n) | 返回从下标位置n开始向后的所有字符作为子字符串 |
有些方法需要以String类使用,有些则用字符串变量来使用
csharp
static void Main(string[] args){
string str = "Hello World!";
string str1 = "Hello";
string str2 = " World!";
Console.WriteLine(String.Concat(str1, str2));
Console.WriteLine(str1.Concat(str2)); // 这句也会输出,但不是期望的内容
Console.WriteLine(str.Substring(6));
Console.WriteLine(str.Replace("World", "New World"));
Console.ReadKey();
}