黑马程序员_iOS开发C语言基础之字符串

1、字符串使用注意

#include <stdio.h>

int main()

{

    char name[] = "itcast";

    name[3] = 'H';

    char name2[] = {'a','b'};

    char name3[] = {'a','b','\0'};    /*

    int size = sizeof(name);

    printf("%d\n",size);//size=7;

    */

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

    printf("%s\n",name2 );//输出内容包括name,值为abitcHst,原因如下图,%s会从数组名name2首地址,开始输出字符,直到遇到’\0’结束

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

    printf("%s\n",&name2[1]);//与占位符匹配的是地址&name2[1],输出结果  为kit.   

    return 0;

}



void test2()

{

    // \0ASCII码值是0

    char name[8] = "it";//数组长度为8,使用了3

    char name2[8] = {'i','t','\0'};//字符串

    char name3[8] = {'i','t',0}; //可以,字符串

    char name4[8] = {'i','t'};//不是严格意义上字符串,但是后默认有60

    char name5[] = {'i','t'}; // 注意不是字符串,只能说是普通的字符数组,不能当做字符串使用。

}

void test()

{

    printf("Jack\n");

    char name[10] = "Jack";

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

    printf(name);// 把数组传入只是一个警告

    printf("ewewf"); // 默认参数为常量   

}

2、字符串函数strlen使用注意

/*

 strlen函数: 计算字符串长度

 1.计算的是字符数,并不是字数

 2.计算的字符不包括\0

 */

//strlen函数声明在string.h文件中

#include <string.h>

#include <stdio.h>

int main()

{

    //int size = strlen("haha");

    //printf("%d\n",size );

    /*

     char name[] = "itcast";

    int size = strlen(name);

    printf("%d\n",size );// 6

    char name2[] = "it\0cast";

    int size2 = strlen(name2);

    printf("%d\n",size2 );// 2

     */

    char name[] = "itcast";

    char name2[] = {'0','6'};

    int size2 = strlen(name2);

    printf("%d\n",size2 );// 8,因为strlenname2地址开始数字符,直到遇到\0结束

char name[] = "itcast";

    printf("%c\n",name[2]); //输出为a


}


3、二维数组的使用

char names[2][10]={"jack","rose"};

    printf("%s\n",names[0]); //输出jack

    printf("%c\n",names[0][3]);//输出k,注意不用地址符&

    char name2[2][10]=

    {

        {'j','a','c','k','\0'},

        {'r','o','s','e','\0'}

    };

代码的编写注意点:可读性 —> 性能 -> 精简(重构)不是代码越少,性能越高


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值