• 字符串的定义方式;输出和计算长度时的细节


    c语言中几种字符串的定义方式:

    第1种:

     char a[5]="hello";

     

     第2种:

     char a[]="hello";

     

    第3种:

     char* a="hello";

     

    第4种:

     char a[10];

    gets(a);

     

    第5种:

     char* a[5]={"hello",

     "nihao",

     "good",

     "ok",

     "bye"};

    1 #include <stdio.h>
    2 #include<stdlib.h>
    3 int main(){
    4 char harder[] = "hello bit.";
    5 printf("%s
    ",harder);
    6 printf("%d
    ", sizeof(harder));
    7 return 0; }

    结论,在vs编译环境下:

    用sizeof计算数组长度,包括 (为结束符)
    例如,“ABCD”的字符数组长度为4,但是存储它的字符数组元素个数,应该为5。
    即至少是char s[5](需要写成char s[5],但用strlen(s)计算时长度为4),用sizeof计算包含,长度为5.

    sizeof 计算    数组长度

    strlen计算     字符串长度

    另外注意,在char s[],在s[]内尽量不要填数字,否则当用sizeof(char)时候,长度不按照实际长度而是[]内你填的长度输出。

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 int main()
     5 {
     6     char str[] = {1,3,5};
     7     printf("%d
    ", sizeof(str));
     8     system("pause");
     9     return 0;
    10 }

    用sizeof,输出结果长度为3

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 int main()
     5 {
     6     char str[6] = {1,3,5};
     7     printf("%d
    ", sizeof(str));
     8     system("pause");
     9     return 0;
    10 }

      用sizeof,输出结果长度为6

  • 相关阅读:
    解题:POI 2006 Periods of Words
    解题:NOI 2014 动物园
    1483. 最高平均分
    1438. 较大分组的位置(回顾)
    1258. 漂亮子数组
    1903. 部门统计(回顾)
    1509. 柠檬水找零
    1451. 到最近的人的最大距离
    1425. 比较含退格的字符串
    1394. 山羊拉丁文
  • 原文地址:https://www.cnblogs.com/hetaoyuan/p/10063932.html
Copyright © 2020-2023  润新知