(三)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';
        }
    }    

}