C语言讲义——字符串库函数

字符串库函数<string.h>

求字符串长度(不含结束符’\0’****) strlen(str)
字符串赋值(可能造成数组越界) strcpy(str," 水浒传 ");
字符串追加(可能造成数组越界) strcat(str," 三国演义 ")
字符串比较(小于:-1/等于:0/大于:1****) strcmp("AAA", "BBB");

strlen:自动无视结束符

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
	char str1[] = "Trump";
	printf("sizeof %d\n", sizeof(str1));
	printf("strlen %d\n", strlen(str1));
	printf("*******************\n");
	char str2[] = "川普";
	printf("sizeof %d\n", sizeof(str2));
	printf("strlen %d\n", strlen(str2));
	return 0;
}

strcpy赋值/复制

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
	// 眼见喜、耳听怒、鼻嗅爱、舌尝思、意见欲、身本忧"
	char str1[]="眼见喜";
	printf("%d\n", sizeof(str1));
	printf("%s\n", str1);

	printf("**strcpy*******************************\n");
	strcpy(str1,"耳听怒");
	printf("%d\n", sizeof(str1));
	printf("%s\n", str1);

	printf("**strcpy不检测大小是否匹配*******************************\n");
	int n1 = 1000;
	printf("新变量:%d\n", n1);
	strcpy(str1,"鼻嗅爱、舌尝思");
	printf("%d\n", sizeof(str1));
	printf("%s\n", str1);
	printf("新变量:%d\n", n1); // n1被破坏了

	return 0;
}

注意:strcpy不检测大小是否匹配

char str1[]="眼见喜";
int n1 = 1000;
strcpy(str1,"鼻嗅爱、舌尝思");

strcat(Concatenate·连接)

注意:strcat也不检测大小是否匹配

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
	char str1[]="眼见喜";
	printf("sizeof %d\n", sizeof(str1));
	printf("strlen %d\n", strlen(str1));
	printf("%s\n", str1);

	printf("**strcat不检测大小是否匹配*******************************\n");
	int n1 = 1000;
	printf("新变量:%d\n", n1);

	strcat(str1, "、耳听怒");

	printf("新变量:%d\n", n1);// 被破坏
	printf("sizeof %d\n", sizeof(str1));
	printf("strlen %d\n", strlen(str1));
	printf("%s\n", str1);

	return 0;
}

strcmp判等

str1str1:1
str2
str3:0
小于:-1
大于:1
等于:0

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
	char str1[200]="a";
	char str2[200]="b";
	char str3[200]="b";
	// 使用==判断是错误的
	printf("str1==str1:%d\n", str1==str1);
	printf("str2==str3:%d\n", str2==str3);// 判断错误

	int nCmp;

	nCmp = strcmp("a", "b");
	printf("小于:%d\n", nCmp);

	nCmp = strcmp("b", "a");
	printf("大于:%d\n", nCmp);

	nCmp = strcmp(str2, str3);
	printf("等于:%d\n", nCmp);

	return 0;
}

字符串转数字

需要#include <stdlib.h>

转整形 int n = atoi(str);
转浮点型(double****) double d = atof(str);
posted @ 2019-07-15 21:29  虎老狮  阅读(352)  评论(0编辑  收藏  举报