← 返回首页
C语言系列教程(十七)
发表时间:2021-03-25 22:57:57
字符数组和字符串

字符串的本质就是字符串数组。

在C语言中,没有专门的字符串变量,没有String类型,通常就用一个字符数组来存放一个字符串。

1.字符串定义

字符串有多种定义方式,如下例:

#include <stdio.h>
#include <stdlib.h>

int main() {

    char str1[6]= {'h','e','l','l','o','\0'}; //指定长度
    char str2[]= {'h','e','l','l','o','\0'}; //不指定长度
    char str3[6]="hello"; //字符串直接赋给数组
    char str4[6]= {"hello"}; //符串直接赋给数组
    char str5[]="hello"; // 指定长度的字符串直接赋给数组
    char* str6="hello"; //使用字符指针

        printf("\n---------out with printf----------------\n");
    printf("%s\n",str1);
    printf("%s\n",str2);
    printf("%s\n",str3);
    printf("%s\n",str4);
    printf("%s\n",str5);
    printf("%s\n",str6);

    printf("\n---------out with puts----------------\n");
    puts(str1);
    puts(str2);
    puts(str3);
    puts(str4);
    puts(str5);
    puts(str6);

    return 0;
}

运行结果:

---------out with printf----------------
hello
hello
hello
hello
hello
hello

---------out with puts----------------
hello
hello
hello
hello
hello
hello

需要注意的是,字符数组只能在定义的同时赋初值,一旦定义完成就一次性的赋初值了,只能给一个字符赋初值。 例如:

#include <stdio.h>
#include <stdlib.h>
int main() {
    char str1[6];
    //str1="hello"; //错误!
    str1[0]='h';
    str1[1]='e';
    str1[2]='l';
    str1[3]='l';
    str1[4]='o';
    str1[5]='\0';
    puts(str1);
    return 0;
}

2.字符串结束符号

在C语言中,字符串总是以'\0'作为结尾,所以'\0'也被称为字符串结束标志,或者字符串结束符。下图演示了"C program"在内存中的存储情形:

实例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {

    char str1[]={'h','e','l','l','o'};//逐个字符地给数组赋值并不会自动添加'\0'
    char str2[]="hello";//整体赋给字符串结尾默认添加'\0' 

    puts(str1);
    puts(str2);

    printf("str1 length is:%d\n",strlen(str1));//注意:strlen方法不计算结束标识符 
    printf("str2 length is:%d\n",strlen(str2));

    printf("str1 size is:%d\n",sizeof(str1));
    printf("str2 size is:%d\n",sizeof(str2));

    return 0;
}

运行结果:

hello
hello
str1 length is:5
str2 length is:5
str1 size is:5
str2 size is:6

实例: 使用循环实现输出26个小写字母组成的字符。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {

    char str1[30]="abcdefghijklmnopqrstuvwxyz";
    char str2[30];
    char str3[30]={0};
    for(int j=0,i=97;i<123;j++,i++){
       str2[j]=i;
       str3[j]=i;
    }
    puts(str1);
    puts(str2);
    puts(str3);
    return 0;
}

运行结果:

abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz