c语言指针和字符串比较strcmp,字符串拷贝strcpy

指针和字符串:        

1.字符串的定义方式:

        1.char str[ ]={'h','e','l','l','o','\0'};        //变量:可读可写

       2. char str[ ]="hello";                //变量:可读可写

       3. char *str='hello';                //常量:只读

	char str1[] = "hello";    //{'h','e','l','l','o','\0'}可以取地址修改
	char* str2 = "hello";    //“hello”是一个字符串常量,无法修改

	printf("str1=%s\n",str1);
	printf("*str2=%s\n",str2);

	system("pause");
	return 0;

输出:

str1=hello
*str2=hello

str2[0]='r'; //指针数组无法被取出 

char *str={'h','e','l','l','o','\0'};        //error,不可以这样写

	char str1[] = "hello";
	char m[] = "hello";

	char* str2 = "hello";
	char *n = "hello";

	printf("str1=%p\n",str1);
	printf("m=%p\n", m);

	printf("*str2=%p\n",str2);
	printf("*n=%p\n", n);

输出: 

str1=000000A7FBCFFCA4
m=000000A7FBCFFCC4
*str2=00007FF796449CA4
*n=00007FF796449CA4

str1和m为变量,指针数组*str2和*n为常量 

c语言指针和字符串比较strcmp,字符串拷贝strcpy_第1张图片

2.当字符串(字符数组)做函数参数时,不需要提供两个参数,因为每个字符串都有‘\0’

字符串比较strcmp(字符比较):

        比较str1和str2,如果相同返回0,不同则依次比较ASCII码,str1>str2返回1,否则返回-1

 

int mystrcmp(char* str1, char* str2) {

	int i = 0;

	while (str1[i] == str2[i]) {
		if (str1[i] == '\0') {
			return 0;		//两字符串比较到结尾,结束函数
		}
		i++;		//未比较到\0符则继续比较
	}
	return str1[i] > str2[i] ? 1: -1;
}

int main(void) {

	char* str1 = "hello";
	char* str2 = "hello";

	int ret = mystrcmp(str1,str2);
	if (ret == 0)
		printf("相同\n");
	else if (ret == 1)
		printf("str1>str2\n");
	else if (ret == -1)
		printf("str2>str1\n");
	else
		printf("异常\n");

	system("pause");
	return EXIT_SUCCESS;
}

字符串拷贝:

两种办法:

void mystrcpy(char* src, char* dst) {
	int i = 0;
	while (src[i] != 0) {
		dst[i] = src[i];
		i++;
	}
	dst[i] = '\0';
}

int main(void) {
	char* src = "hello";

	char dst[100] = { 0 };

	mystrcpy(src, dst);

	printf("dst=%s\n",dst);

	system("pause");
	return EXIT_SUCCESS;

}
//数组版本

输出:

dst=hello

 

void mystrcpy2(char* src, char* dst) {
	while (*src!='\0') {			//src[i]==**(src+i);
		*dst = *src;
		src++;
		dst++;
	}
    *dst='\0';
}


int main(void) {
	char* src = "hello";

	char dst[100] = { 0 };

	mystrcpy2(src, dst);

	printf("dst=%s\n",dst);

	system("pause");
	return EXIT_SUCCESS;

}
//指针版

输出:

dst=hello

你可能感兴趣的:(自学笔记,c语言)