C语言中的字符串操作
本文梳理总结了C语言中的常见字符串操作
读入
scanf("%s", s)
读入一个字符串,以空格和换行为分界
gets(s)
可以直接输入带空格的一行字符串,系统会将最后的换行符从缓冲区中取出然后丢弃
gets()
输入后自动添加'\0'
fgets()
函数原型
1
2
char *fgets(char *s, int size, FILE *stream);参数含义
s
代表要保存到的内存空间的首地址,可以是字符数组名,也可以是指向字符数组的字符指针变量名size
代表的是读取字符串的长度stream
表示从何种流中读取,可以是标准输入流stdin
,也可以是文件流
补充说明
- 比
gets
函数更安全 fgets
的中间size参数直接赋值字符数组长度即可- 如果输入字符串长度没有超过
size-1
那么系统会将最后输入的换行符'\n'
保存,剩余空间都用'\0'
填充。所以输出时不用再加换行符'\n'
- 比
比较
比较方法:
bcmp()
,比较字符串的前n个字节是否相等;2.strcmp()
,区分大小写地比较字符串;stricmp()
,不区分大小写地比较字符串;strncmp()
或strnicmp()
,区分大小写地比较字符串的前n个字符。
strcmp
原型为
1 | int strcmp(const char *s1, const char *s2); |
【返回值】若参数s1 和s2 字符串相同则返回0。s1 若大于s2 则返回大于0 的值。s1 若小于s2 则返回小于0 的值。
拷贝
strcpy
原型为
1 | char* strcpy(char* des,const char* source){ |
分割
strtok
strtok
breaks string str into a series
of tokens using the delimiter.
将delimiter
部分的字符转化为\0
函数原型
1
char *strtok(char *str, const char *delim)
返回值
函数返回指向分割后第一个字符串的指针。如果没有子串,返回NULL
示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main () {
char str[80] = "This is - www.tutorialspoint.com - website";
const char s[2] = "-";
char *token;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, s);
}
return(0);
}
连接
strcat()
将s2字符串连接到s1的后面,包括空字符
s1长度需要足够大,以容纳连接的字符串
函数原型
1
char* strcat(char* s1, const char* s2);
strncat()
函数原型
1
char* strncat(char* s1, const char*s2, size_t n)
参数
n
: 附加的字符串的最大长度
大小写转换
strlwr()
将字符串中大写字母换成小写字母
函数原型
1
char* strlwr(char* s);
strupr()
将字符串中大写字母换成小写字母
函数原型
1
char* strlwr(char* s);
转换为数值
与非法字符停止转换,非法的字符也有返回值
需要引入头文件<stdlib.h>
atof()
函数原型
1
double atof(const char* ns);
atoi()
函数原型
1
int atoi(const char* ns);
输出
puts()
直接输出一行字符串,末尾加上\n
scanf
输入double
时必须使用%lf