字符串+转义字符+注释
字符串
"hello bit.\n"
这种由双引号(Double Quote)引起来的一串字符称为字符串字面值(String Literal),或者简称字符串。
#include <stdio.h>
#include <stdlib.h>
int main()
{
"abcdef";
"";///空字符串
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
char arr1[] = "abc";///数组
char arr2[] = {'a', 'b', 'c'};///用单引号引起来的表示字符
printf("%s\n",arr1);
printf("%s\n",arr2);
return 0;
}
///打印结果:
///abc
///abcabc
如果这时在arr2[]中加一个0会发生什么?
#include <stdio.h>
#include <stdlib.h>
int main()
{
char arr1[] = "abc";///用字符数组保存字符串
char arr2[] = {'a', 'b', 'c',0};///用单引号引起来的表示字符
///写0和'\0'都可以,每一个字符都有对应的值,'\0'对应0,'a'对应97,即ASCII码值
printf("%s\n",arr1);
printf("%s\n",arr2);
return 0;
}
///打印结果:
///abc
///abc
可以看到第二行的打印结果变成了abc
为什么会出现这种情况呢?
arr1中的"abc"的组成为—‘a’,‘b’,‘c’,‘\0’—其中’\0’是字符串结束的标志
arr2中没有\0,则在abc后生成一些随机值,codeblock中是abc
注:字符串的结束标志是一个\0的转义字符。在计算字符串长度的时候\0是结束字符,不算作字符串内容。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char arr1[] = "abc";
char arr2[] = {'a','b','c',0};///如果没有0则还要加上随机值的长度
printf("%d\n",strlen(arr1));
printf("%d\n",strlen(arr2));
///strlen即string length,用于计算字符串长度
return 0;
}
///打印结果:
///3
///3
转义字符
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("abc\n");/// \n换行
return 0;
}
转义字符:转变原来的意思
转义字符 | 释义 |
---|---|
\t | 水平制表符 |
\v | 垂直制表符 |
\n | 换行 |
\r | 回车 |
? | 在书写连续多个问号时使用 ,防止被解析成三字母词 |
\’ | 用于表示字符常量’ |
\" | 用于表示一个字符串内部的双引号 |
\\ | 用于表示一个反斜杠,防止它被解释为一个转义序列符 |
\a | 警告符号,蜂鸣 |
\b | 退格符 |
\ddd | ddd表示1~3个八进制的数字。如:\130 X |
\xdd | dd表示2个十六进制数字。如:\x30 0 |
\'和\"
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("%c\n",'\'');/// \'的使用
///%c表示输出字符
///如果不加\,编译器只会识别前面两个单引号,且两个单引号之间没有字符
printf("%s\n","\"");/// \"的使用,和上面同理
///%s表示输出字符串
return 0;
}
///打印结果:
///'
///"
\ddd
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("%d\n",strlen("c:\test\32\test.c"));///看上去是17个字符
/// 转义字符是1个字符,\t,\32
/// \32,32是两个8进制数字
/// 32转换成十进制后的数字是26,26作为ASCII码值对应的字符
printf("%c\n",'\32');///26对应的ASCLL码值
printf("%c\n",'\130');///90对应的ASCII码值
return 0;
}
///打印结果:
///13
///
///X
\xdd
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("%c\n",'\x61');
printf("%c\n",'\x30');
}
///打印结果:
///a
///0
注释
1.代码中有不需要的代码可以直接删除,也可以直接注释掉
2.代码中有些代码比较难懂,可以加一下注释文字
注释有两种风格:
1.C语言风格的注释 /* xxxxxxxxxx */
缺点:不能嵌套,以/* 开始,以之后的第一个 */结束
2.C++风格的注释 //xxxxxxxxxxx
注:我的代码里用///只是因为在codeblock里///的注释比较好看(哈哈