sda
第20课 字符串的声明和简单拼接操作
1. char a = '1';
int b = a;
Console.WriteLine(a);
Console.WriteLine(b);
输出结果为:1
49
注:当字符类型为字符串类型char时,‘1’输出为字符串1,不是数字而是字符串,不能参与运算的1,当赋值给整数型b以后,字符‘1’则变成了相应的数字49存储在整数类型名为b中。
2. \ 为转义字符。
char a = '\n'; //输出为n。
char a = '\\'; //输出为\。
char a = '\"'; //输出为"。
3. Console.WriteLine("c:\\a\\b\\c");
Console.WriteLine(@"c:\a\b\c");
它们的输出结果都为:c:\a\b\c
其中@的用法是将引号内的转义字符\失效,而第一个里面的("c:\\a\\b\\c")转义字符都有效。
4. 字符串的声明:
string str = @ "c:\\a\\b\\c";
声明字符串,加@符号后,双引号中的\字符就没有转义的功能,直接就是c:\\a\\b\\c,加@符号的字符串是可以换行的,并且输出后保持换行。
5. 如何在@"c:\\a\\b\\c"中加入引号:
@"c:\\a\\b\\c"中可以用两个引号("")表示加入一个引号。
例如:
string str = @ "c:\a\""b\c";
Console.WriteLine(str);
输出的结果为:c:\a\""b\c
6. 字符串拼接的几种形式:
①string str = "123" + "456";
Console.WriteLine(str);
输出结果为:123456
②也可以用变量+字符串来拼接:
string str = "123" + "456";
string str2 = "str"+yyyy;
Console.WriteLine(str2);
输出结果为:123456yyyy
③Console.WriteLine("www"+123);
输出结果为:www123
注:用+将两段字符串拼接在一起,+两端的字符串都分别用引号引起来。
7. char和string的区别:
char是字符类型,string是字符串类型。String可以看作是char组成的列表。