c 语言中字符串详解以及条件运算符的特殊例子

1 字符创初始化的方式:

    char str[10]={ 'I',' ','a','m',' ',‘h’,'a','p','p','y'}; 

  char str[10]={"I am happy"};  

  char str[10]="I am happy";  


  char str[14]; 

   str="I love China"//错误,不是初始化,这是赋值,只能一一进行。 

   char *str;  

   str = "I love China";   //  这样子是可以的

   char * str =  "I love China";   //  这样子也是是可以的


2  字符串数组初始化为空:

(1) char str[10]="";
(2) char str[10]={'\0'};
(3) char str[10]; str[0]='\0'; //这个只有第一个初始化为空

(4)char str[10]={0};  

  memset(str,'\0',sizeof(str));    //c 语言下的头文件 #include<memory.h> 

3 关于字符串strlen和sizeof

        char str[10]={"I ha ppy"};
        char str1[] ="I am lei";
        char *str2="I am lei";
        int a1 = sizeof(str); //10
        int a2 =strlen(str);  //8 
      
        int b1 = sizeof(str1);//9
        int b2= strlen(str1); //8
    
        int c1 =  sizeof(str2);//8
        int c2= strlen(str2); //8           
    
        printf("%d,%d,%d,%d,%d,%d\n",a1,a2,b1,b2,c1,c2); 

    输出结果是:10,8,9,8,8,8  

    strlen 是一个函数,计算的是字符串的实际长度,sizeof计算的是数组占有的长度。

    sizeof 是一种单目运算符和++ ,-- 一样   关键字可以用于对一个表达式的计算结果求大小,但是这个表达式在运行的过程中不会真正的执行

     char ch = 'c';

     printf("%d",sizeof(ch = 'd'));

     printf("%c",ch);//结果显示的还是‘c’;

     在gcc中   printf("%d",sizeof(ch)); 这段代码是编译通不过的。 必须要这样写才可以 printf("%ld",sizeof(ch));  因为sizeof返回的是长整型

     sizeof还有一个特俗情况:

     char *ptr ="C";
     char ch =  'c';   
     printf("%ld\n",sizeof(ch)); //1     
     printf("%ld\n",sizeof('c')); //4 因为这个是常量   
     printf("%ld\n",sizeof( ptr)); //8 指针的大小(在linux中是8)      


4  关于字符串中几个常见的函数: 

 这些函数的头文件是:#include<string.h>

  1) strcat  函数

      char str1[20]="hello";
      char *str2= "china";
      strcat(str1,str2); //  将str2放在str1 后面连接起来,保存在str1中,记住要保证str1的宽度足够长,否则会报内存错误。

      strcat(str2,str1); //这样子的做法是错误的,str2不能是指针字符串。

  2) strcpy  函数

    char str1[8]="hello";
        char *str2= "chd";
        strcpy(str1,str2);  // 将str1的数据情空,将str2的内容拷贝到str1中 ,记住 str1的内存空间必须要比str2的要大,否则会报错
     

         strcpy(str2,str1) ;//这样子是会报错的,第一个参数不能是指针字符串。

  3) strncpy 

char str1[8]="hello";
        char *str2= "chd";
        strncpy(str1,str2,3);
   //将str2中的三个字符拷贝到str1中,输出的结果是chdlo;

  4) strlwr(str);  将大写字母转换为小写字母  //这两个函数不是标准的C 函数,只能在vc中使用

  5) strupr(str); 将小写字母转换为大写字母 //这两个函数不是标准的C 函数,只能在vc中使用


5 关于条件运算符

  条件运算符是从左往右进行计算的。

  max = a>b? a:b;

  max = a >b ? a:c>d?c:d    因为条件运算符是从左往右计算的, 故此语句等于 max = a> b? a:(c>d ?c:d);



 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值