• C语言字符数组与字符串


    5.5.1 字符数组与字符串区别

    l  C语言中没有字符串这种数据类型,可以通过char的数组来替代;

    l  字符串一定是一个char的数组,但char的数组未必是字符串;

    l  数字0(和字符‘\0’等价)结尾的char数组就是一个字符串,但如果char数组没有以数字0结尾,那么就不是一个字符串,只是普通字符数组,所以字符串是一种特殊的char的数组。

     

     1 #include <stdio.h>
     2 
     3  
     4 
     5 int main()
     6 
     7 {
     8 
     9        char c1[] = { 'c', ' ', 'p', 'r', 'o', 'g' }; //普通字符数组
    10 
    11        printf("c1 = %s\n", c1); //乱码,因为没有’\0’结束符
    12 
    13  
    14 
    15        //以‘\0’(‘\0’就是数字0)结尾的字符数组是字符串
    16 
    17        char c2[] = { 'c', ' ', 'p', 'r', 'o', 'g', '\0'};
    18 
    19        printf("c2 = %s\n", c2);
    20 
    21  
    22 
    23        //字符串处理以‘\0’(数字0)作为结束符,后面的'h', 'l', 'l', 'e', 'o'不会输出
    24 
    25        char c3[] = { 'c', ' ', 'p', 'r', 'o', 'g', '\0', 'h', 'l', 'l', 'e', 'o', '\0'};
    26 
    27        printf("c3 = %s\n", c3);
    28 
    29  
    30 
    31        return 0;
    32 
    33 }
    34 
    35  

    5.5.2 字符串的初始化

     1 #include <stdio.h>
     2 
     3  
     4 
     5 // C语言没有字符串类型,通过字符数组模拟
     6 
     7 // C语言字符串,以字符‘\0’, 数字0
     8 
     9 int main()
    10 
    11 {
    12 
    13        //不指定长度, 没有0结束符,有多少个元素就有多长
    14 
    15        char buf[] = { 'a', 'b', 'c' };
    16 
    17        printf("buf = %s\n", buf); //乱码
    18 
    19  
    20 
    21        //指定长度,后面没有赋值的元素,自动补0
    22 
    23        char buf2[100] = { 'a', 'b', 'c' };
    24 
    25        printf("buf2 = %s\n", buf2);
    26 
    27  
    28 
    29        //所有元素赋值为0
    30 
    31        char buf3[100] = { 0 };
    32 
    33  
    34 
    35        //char buf4[2] = { '1', '2', '3' };//数组越界
    36 
    37  
    38 
    39        char buf5[50] = { '1', 'a', 'b', '0', '7' };
    40 
    41        printf("buf5 = %s\n", buf5);
    42 
    43  
    44 
    45        char buf6[50] = { '1', 'a', 'b', 0, '7' };
    46 
    47        printf("buf6 = %s\n", buf6);
    48 
    49  
    50 
    51        char buf7[50] = { '1', 'a', 'b', '\0', '7' };
    52 
    53        printf("buf7 = %s\n", buf7);
    54 
    55  
    56 
    57        //使用字符串初始化,编译器自动在后面补0,常用
    58 
    59        char buf8[] = "agjdslgjlsdjg";
    60 
    61  
    62 
    63        //'\0'后面最好不要连着数字,有可能几个数字连起来刚好是一个转义字符
    64 
    65        //'\ddd'八进制字义字符,'\xdd'十六进制转移字符
    66 
    67        // \012相当于\n
    68 
    69        char str[] = "\012abc";
    70 
    71        printf("str == %s\n", str);
    72 
    73  
    74 
    75        return 0;
    76 
    77 }

     

    5.5.3 字符串的输入输出

    由于字符串采用了'\0'标志,字符串的输入输出将变得简单方便。

     1 #include <stdio.h>
     2 
     3  
     4 
     5 int main()
     6 
     7 {
     8 
     9        char str[100];
    10   
    11 
    12        printf("input string1 : \n");
    13 
    14        scanf("%s", str);//scanf(“%s”,str)默认以空格分隔
    15 
    16        printf("output:%s\n", str);
    17 
    18  
    19 
    20        return 0;
    21 
    22 }
    23 
    24  

    5.5.4 强化训练:字符串追加

     1 #include <stdio.h>
     2 
     3  
     4 
     5 int main()
     6 
     7 {
     8 
     9        char str1[] = "abcdef";
    10 
    11        char str2[] = "123456";
    12 
    13        char dst[100];
    14 
    15  
    16 
    17        int i = 0;
    18 
    19        while (str1[i] != 0)
    20 
    21        {
    22 
    23               dst[i] = str1[i];
    24 
    25               i++;
    26 
    27        }
    28 
    29  
    30 
    31        int j = 0;
    32 
    33        while (str2[j] != 0)
    34 
    35        {
    36 
    37               dst[i + j] = str2[j];
    38 
    39               j++;
    40 
    41        }
    42 
    43        dst[i + j] = 0; //字符串结束符
    44 
    45  
    46 
    47        printf("dst = %s\n", dst);
    48 
    49  
    50 
    51        return 0;
    52 
    53 }
    54 
    55  

    5.5.5 函数的调用:产生随机数

    当调用函数时,需要关心5要素:

    l  头文件:包含指定的头文件

    l  函数名字:函数名字必须和头文件声明的名字一样

    l  功能:需要知道此函数能干嘛后才调用

    l  参数:参数类型要匹配

    l  返回值:根据需要接收返回值

     

    #include <time.h>

    time_ttime(time_t *t);

    功能:获取当前系统时间

    参数:常设置为NULL

    返回值:当前系统时间, time_t 相当于long类型,单位为毫秒

    #include <stdlib.h>

    voidsrand(unsignedintseed);

    功能:用来设置rand()产生随机数时的随机种子

    参数:如果每次seed相等,rand()产生随机数相等

    返回值:无

    #include <stdlib.h>

    intrand(void);

    功能:返回一个随机数值

    参数:无

    返回值:随机数

     

     1 #include <stdio.h>
     2 
     3 #include <time.h>
     4 
     5 #include <stdlib.h>
     6 
     7  
     8 
     9 int main()
    10 
    11 {
    12 
    13        time_t tm = time(NULL);//得到系统时间
    14 
    15        srand((unsigned int)tm);//随机种子只需要设置一次即可
    16 
    17  
    18 
    19        int r = rand();
    20 
    21        printf("r = %d\n", r);
    22 
    23  
    24 
    25        return 0;
    26 
    27 }
    28 
    29  

    5.5.6 字符串处理函数

    1) gets()

    #include <stdio.h>

    char *gets(char *s);

    功能:从标准输入读入字符,并保存到s指定的内存空间,直到出现换行符或读到文件结尾为止。

    参数:

           s:字符串首地址

    返回值:

           成功:读入的字符串

           失败:NULL

     

    gets(str)与scanf(“%s”,str)的区别:

    l  gets(str)允许输入的字符串含有空格

    l  scanf(“%s”,str)不允许含有空格

     

    注意:由于scanf()和gets()无法知道字符串s大小,

    必须遇到换行符或读到文件结尾为止才接收输入,因此容易导致字符数组越界(缓冲区溢出)的情况。

           char str[100];

           printf("请输入str: ");

           gets(str);

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

    2) fgets()

    #include <stdio.h>

    char *fgets(char *s, intsize, FILE *stream);

    功能:从stream指定的文件内读入字符,保存到s所指定的内存空间,

    直到出现换行字符、读到文件结尾或是已读了size - 1个字符为止,最后会自动加上字符 '\0' 作为字符串结束。

    参数:

           s:字符串

           size:指定最大读取字符串的长度(size - 1)

           stream:文件指针,如果读键盘输入的字符串,固定写为stdin

    返回值:

           成功:成功读取的字符串

           读到文件尾或出错: NULL

     

    fgets()在读取一个用户通过键盘输入的字符串的时候,同时把用户输入的回车也做为字符串的一部分。

    通过scanf和gets输入一个字符串的时候,不包含结尾的“\n”,但通过fgets结尾多了“\n”。fgets()函数是安全的,不存在缓冲区溢出的问题。

     

           char str[100];

           printf("请输入str: ");

           fgets(str, sizeof(str), stdin);

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

     

    3) puts()

    #include <stdio.h>

    intputs(constchar *s);

    功能:标准设备输出s字符串,在输出完成后自动输出一个'\n'。

    参数:

           s:字符串首地址

    返回值:

           成功:非负数

           失败:-1

     

    #include <stdio.h>

    int main()

    {

           printf("hello world");

           puts("hello world");

           return 0;

    }

     

    4) fputs()

    #include <stdio.h>

    int fputs(constchar * str, FILE * stream);

    功能:将str所指定的字符串写入到stream指定的文件中, 字符串结束符 '\0'  不写入文件。

    参数:

           str:字符串

           stream:文件指针,如果把字符串输出到屏幕,固定写为stdout

    返回值:

           成功:0

           失败:-1

     

    fputs()是puts()的文件操作版本,但fputs()不会自动输出一个'\n'。

     

           printf("hello world");

           puts("hello world");

           fputs("hello world", stdout);

     

    5) strlen()

    #include <string.h>

    size_tstrlen(constchar *s);

    功能:计算指定指定字符串s的长度,不包含字符串结束符‘\0’

    参数:

    s:字符串首地址

    返回值:字符串s的长度,size_t为unsigned int类型

     

           char str[] = "abcdefg";

           int n = strlen(str);

           printf("n = %d\n", n);

    6) strcpy()

    #include <string.h>

    char *strcpy(char *dest, constchar *src);

    功能:把src所指向的字符串复制到dest所指向的空间中,'\0'也会拷贝过去

    参数:

           dest:目的字符串首地址

           src:源字符首地址

    返回值:

           成功:返回dest字符串的首地址

           失败:NULL

     

    注意:如果参数dest所指的内存空间不够大,可能会造成缓冲溢出的错误情况。

     

    char dest[20] = "123456789";

           char src[] = "hello world";

           strcpy(dest, src);

           printf("%s\n", dest);

     

    7) strncpy()

    #include <string.h>

    char *strncpy(char *dest, constchar *src, size_tn);

    功能:把src指向字符串的前n个字符复制到dest所指向的空间中,是否拷贝结束符看指定的长度是否包含'\0'。

    参数:

           dest:目的字符串首地址

           src:源字符首地址

           n:指定需要拷贝字符串个数

    返回值:

           成功:返回dest字符串的首地址

           失败:NULL

     

           char dest[20] ;

           char src[] = "hello world";

           strncpy(dest, src, 5);

           printf("%s\n", dest);

           dest[5] = '\0';

           printf("%s\n", dest);

     

    8) strcat()

    #include <string.h>

    char *strcat(char *dest, constchar *src);

    功能:将src字符串连接到dest的尾部,‘\0’也会追加过去

    参数:

           dest:目的字符串首地址

           src:源字符首地址

    返回值:

           成功:返回dest字符串的首地址

           失败:NULL

     

           char str[20] = "123";

           char *src = "hello world";

           printf("%s\n", strcat(str, src));

     

    9) strncat()

    #include <string.h>

    char *strncat(char *dest, constchar *src, size_tn);

    功能:将src字符串前n个字符连接到dest的尾部,‘\0’也会追加过去

    参数:

           dest:目的字符串首地址

           src:源字符首地址

           n:指定需要追加字符串个数

    返回值:

           成功:返回dest字符串的首地址

           失败:NULL

     

           char str[20] = "123";

           char *src = "hello world";

           printf("%s\n", strncat(str, src, 5));

     

    10) strcmp()

    #include <string.h>

    intstrcmp(constchar *s1, constchar *s2);

    功能:比较 s1 和 s2 的大小,比较的是字符ASCII码大小。

    参数:

           s1:字符串1首地址

           s2:字符串2首地址

    返回值:

           相等:0

           大于:>0

           小于:<0

          

     

    char *str1 = "hello world";

           char *str2 = "hello mike";

           if (strcmp(str1, str2) == 0)

           {

                  printf("str1==str2\n");

           }

           else if (strcmp(str1, str2) > 0)

           {

                  printf("str1>str2\n");

           }    

           else

           {

                  printf("str1<str2\n");

           }

     

    11) strncmp()

    #include <string.h>

    intstrncmp(constchar *s1, constchar *s2, size_tn);

    功能:比较 s1 和 s2 前n个字符的大小,比较的是字符ASCII码大小。

    参数:

           s1:字符串1首地址

           s2:字符串2首地址

           n:指定比较字符串的数量

    返回值:

           相等:0

           大于: > 0

           小于: < 0

          

    char *str1 = "hello world";

           char *str2 = "hello mike";

           if (strncmp(str1, str2, 5) == 0)

           {

                  printf("str1==str2\n");

           }

           else if (strcmp(str1, "hello world") > 0)

           {

                  printf("str1>str2\n");

           }

           else

           {

                  printf("str1<str2\n");

           }

     

    12) sprintf()

    #include <stdio.h>

    intsprintf(char *_CRT_SECURE_NO_WARNINGS, constchar *format, ...);

    功能:根据参数format字符串来转换并格式化数据,然后将结果输出到str指定的空间中,直到出现字符串结束符 '\0'  为止。

    参数:

           str:字符串首地址

           format:字符串格式,用法和printf()一样

    返回值:

           成功:实际格式化的字符个数

           失败: - 1

     

           char dst[100] = { 0 };

           int a = 10;

           char src[] = "hello world";

           printf("a = %d, src = %s", a, src);

           printf("\n");

           int len = sprintf(dst, "a = %d, src = %s", a, src);

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

           printf("len = %d\n", len);

     

    13) sscanf()

    #include <stdio.h>

    intsscanf(constchar *str, constchar *format, ...);

    功能:从str指定的字符串读取数据,并根据参数format字符串来转换并格式化数据。

    参数:

           str:指定的字符串首地址

           format:字符串格式,用法和scanf()一样

    返回值:

           成功:参数数目,成功转换的值的个数

           失败: - 1

     

           char src[] = "a=10, b=20";

           int a;

           int b;

           sscanf(src, "a=%d,  b=%d", &a, &b);

           printf("a:%d, b:%d\n", a, b);

     

    14) strchr()

    #include <string.h>

    char *strchr(const char *s, int c);

    功能:在字符串s中查找字母c出现的位置

    参数

           s:字符串首地址

           c:匹配字母(字符)

    返回值

           成功:返回第一次出现的c地址

           失败:NULL

     

           char src[] = "ddda123abcd";

           char *p = strchr(src, 'a');

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

     

    15) strstr()

    #include <string.h>

    char *strstr(constchar *haystack, constchar *needle);

    功能:在字符串haystack中查找字符串needle出现的位置

    参数:

           haystack:源字符串首地址

           needle:匹配字符串首地址

    返回值:

           成功:返回第一次出现的needle地址

           失败:NULL

     

           char src[] = "ddddabcd123abcd333abcd";

           char *p = strstr(src, "abcd");

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

    16) strtok()

    #include <string.h>

    char *strtok(char *str, constchar *delim);

    功能:来将字符串分割成一个个片段。当strtok()在参数s的字符串中发现参数delim中包含的分割字符时,

    则会将该字符改为\0 字符,当连续出现多个时只替换第一个为\0。

    参数:

           str:指向欲分割的字符串

           delim:为分割字符串中包含的所有字符

    返回值:

           成功:分割后字符串首地址

           失败:NULL

     

    l  在第一次调用时:strtok()必需给予参数s字符串

    l  往后的调用则将参数s设置成NULL,每次调用成功则返回指向被分割出片段的指针

     

           char a[100] = "adc*fvcv*ebcy*hghbdfg*casdert";

           char *s = strtok(a, "*");//将"*"分割的子串取出

           while (s != NULL)

           {

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

                  s = strtok(NULL, "*");

           }

     

    17) atoi()

    #include <stdlib.h>

    intatoi(constchar *nptr);

    功能:atoi()会扫描nptr字符串,跳过前面的空格字符,直到遇到数字或正负号才开始做转换,

    而遇到非数字或字符串结束符('\0')才结束转换,并将结果返回返回值。

    参数:

           nptr:待转换的字符串

    返回值:成功转换后整数

     

    类似的函数有:

    l  atof():把一个小数形式的字符串转化为一个浮点数。

    l  atol():将一个字符串转化为long类型

     

           char str1[] = "-10";

           int num1 = atoi(str1);

           printf("num1 = %d\n", num1);

           char str2[] = "0.123";

           double num2 = atof(str2);

           printf("num2 = %lf\n", num2);

  • 相关阅读:
    多项式全家桶学习笔记
    [题解] Luogu P2000 拯救世界
    [题解] LuoguP4389 付公主的背包
    [题解] CF438E The Child and Binary Tree
    拉格朗日插值法
    bzoj2788: [Poi2012]Festival
    暑假集训test-8-29
    luoguP4768 [NOI2018]归程
    HDU6331Problem M. Walking Plan
    暑假集训test-8-28
  • 原文地址:https://www.cnblogs.com/MetaWang/p/9876647.html
Copyright © 2020-2023  润新知