(三)C语言之字符串与字符串函数

温馨提示

写博客是为了记录在开发过程中所涉及到的技术以及遇到的问题的解决,如果该博客对您有所帮助,希望可以点个关注;如果您对文章中的内容有什么不同的见解,欢迎留言进行讨论。谢谢!

(三)C语言之字符串与字符串函数

字符串与字符串函数

1. 字符串

  • 使用字符数组存储字符串,\0 表示结束符,字符串可以被修改
void main(){
    char str[] = {'c','h','i','n','a','\0'};
    //char str[6] = {'c','h','i','n','a'};
    //char str[10] = "china";
    printf("%s\n",str);
    str[0] = 's';
    printf("%s\n",str);
    printf("%#x\n",str);
    getchar();
}

输出结果为:

china
shina
0xd9fd64
  • 使用字符指针存储字符串,字符串不能被修改
void main(){
    //内存连续排列
    char *str = "how are you?";
    //字符串不能被修改
    //str[0] = "w";
    //
    // str += 1;
    //*str = 'y';
    printf("%s\n",str);
    printf("%#x\n",str);
    getchar();
}

输出结果为:

how are you?
0x967be4

2. 字符串相关函数

在线API文档

  • strcat 字符串拼接函数
  • strcpy 字符串复制函数
void main(){
    char dest[50];
    char *a = "china";
    char *b = " is powerful!"
    //将数组a复制到数组dest中
    strcpy(dest,a);
    //将数组b拼接到数组dest上
    strcat(dest,b);
    printf("%s\n",dest);
    
    getchar();
}

输出结果为:

china is powerful!
  • strchr 在一个字符串中查找给定字符的第1个匹配的之处
 void main(void){
	char *haystack = "I want go to USA!";
	char *needle = "to";
	//U元素的指针
	
	char* p = strstr(haystack, needle);
	if (p){
		printf("索引位置:%d\n", p - haystack);
	}
	else{
		printf("没有找到");
	}

	system("pause");
}
  • strcmp 比较字符串
  • strcmpi 比较字符串,忽略大小写
void main(void){
	char *str1 = "abc";
	char *str2 = "ABC";
	//int r = strcmpi(str1, str2);
	int r = _strcmpi(str1, str2);
	printf("%d\n",r);
	//str1 > str2
	if (r > 0){
		printf("str1 大于str2\n");
	}
	else if (r == 0){
		printf("str1 等于str2\n");
	}
	//str1 < str2
	else if (r < 0){
		printf("str1 小于str2\n");
	}

	system("pause");
}
  • strset 把字符串s中的所有字符都设置成字符c
void main(void){
	char str[] = "internet change the world!";
	_strset(str,'w');
	printf("%s\n",str);
	system("pause");
}
  • strrev 把字符串s的所有字符的顺序颠倒过来
void main(void){
	char str[] = "internet change the world!";
	_strrev(str);
	printf("%s\n", str);
	system("pause");
}
  • atoi 字符串转为int类型
  • atol():将字符串转换为长整型值
void main(void){
	char* str = "a78";
	//int r = atoi(str);	
	printf("%d\n", r);

	system("pause");
}

  • strtod:字符串转为double类型
void main(void){
	char* str = "77b8b";
	char** p = NULL;
	//char* p = str + 2;
	//参数说明:str为要转换的字符串,endstr 为第一个不能转换的字符的指针
	double r = strtod(str,p);
	printf("%lf\n", r);
	printf("%#x\n", p);

	system("pause");
}
  • strupr转换为大写
void main(void){
	char str[] = "CHINA motherland!";
	_strupr(str);
	printf("%s\n",str);
	system("pause");
}
  • 转换为小写
void mystrlwr(char str[],int len){
	int i = 0;
	for (; i < len; i++){
		//A-Z 字母 a-Z
		if (str[i] >= 'A' && str[i] <= 'Z'){
			str[i] = str[i]-'A' + 'a';
		}
	}	

}

发布了43 篇原创文章 · 获赞 38 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_20538515/article/details/88247876