zoukankan      html  css  js  c++  java
  • 字符串的定义方式;输出和计算长度时的细节

    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

  • 相关阅读:
    原生js可爱糖果数字时间特效
    jQuery绑定事件的四种方式
    jQuery选择器总结
    正则表达式
    this对象
    网页瀑布流效果实现的几种方式
    关于DOM
    SparkSQL读写外部数据源--数据分区
    SparkSQL读写外部数据源-通过jdbc读写mysql数据库
    SparkSQL读写外部数据源-基本操作load和save
  • 原文地址:https://www.cnblogs.com/hetaoyuan/p/10063932.html
Copyright © 2011-2022 走看看