字符串:以字符
'\0'
(ASCII值为0的一个特殊标识符)结尾的字符(char)数组
不是所有的字符数组都是字符串,字符串都是特殊的字符数组
char greet[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greet[] = "Hello";
char *greet = "Hello";

输入 / 打印字符串
- 打印字符串的单个字符(%c):
char *greet = "Hello";
printf("%c %c\n", greet[0], greet[1]);
//输出:H e
- 打印字符串(%s):
- new_greet是字符数组名(指向第一个元素的指针)
char new_greet[] = "Hello World";
printf("%s\n", new_greet);
//输出:Hello World
- 输入字符串(%s):
- 会跳过开头的任意空格
- 当出现空格或者EOF时结束
- 自动在末尾插入'\0'
scanf("%s", word);
strcpy 函数
strcpy(s1, s2);
- 将s2的值拷贝给s1,目标字符串必须有足够的空间来存放原字符串(包括
'\0'
),否则会有缓存溢出的风险 - 不能使用
'='
来复制(仅拷贝的同一个字符串的地址)
#define LEN 12
char greet_one[] = "Hello World";
char new_str[LEN];
strcpy(new_str, greet_one);
printf("%s\n", new_str);
strcpy(new_str, "Good Bye");
printf("%s\n", new_str);
//输出
//Hello World
//Good Bye
strlen 函数
strlen(s1);
-
计算字符串长度,不计算末尾的
'\0'
char new_greet[] = "Hello World"; printf("Length = %d\n", strlen(new_greet)); //输出:Length = 11
strcmp 函数
strcmp(s1, s2) ;
-
比较两个字符串是否相同,相同就返回0,
s1 < s2
则返回负数,s1 > s2
则返回正数 -
比较方式是逐个比较每一位的ASCII码数值
-
不能使用
"=="
比较char greet_one[] = "Hello World"; char greet_two[] = "Hello WORLD"; if (strcmp(greet_one, greet_two) == 0) printf("Strings are identical.\n"); else printf("Strings are not identical.\n"); //输出:Strings are not identical.
其余的 <string.h> 库函数
-
strcat(s1, s2) : 将
s2
链接到s1
的末尾 -
strchr(s1, ch):返回一个指向字符
ch
第一次在s1
中出现位置的指针 -
strstr(s1, s2):返回一个指向字符串
s2
第一次在s1
中出现位置的指针
网友评论