zoukankan      html  css  js  c++  java
  • C语言中的字符和字符串

    C语言在中常常出现字符和字符串,而一串字符或者字符串其实就是数组

    字符数组的定义

    char arr[]={'h','e','l','l','o',''};

    而定义字符串:

    char arr1[]="HELLO";

    字符的输入和输出可以向一维数组那样用scanf和printf,而字符也可以用自己特定输入和输出函数gerchar和putchar,而用getchar和putchar输入一串字符

        char arr[1000];
        int i=0,j=0;
        char ch;
        while ((ch=getchar())!='
    ') {
            arr[i]=ch;
            i++;
        }
        arr[i]='';
        while (arr[j]!='') {
            putchar(arr[j]);
            j++;
        }
        printf("
    ");

    输出结果:

    字符串也有自己特定的输入和输出函数

       // gets和puts 字符串的输入和输出
        char ch[100];
        gets(ch);
        puts(ch);

    字符串的相关库函数部分:需要导入头文件

    #include <string.h>
      char str1[30]="wfds";
    
        char str2[]="zfds";
    
        strcpy(str1, str2);//把str2复制到str1中,str1的长度要比str2大
    
        puts(str1);
    
        puts(str2);
    
        strcat(str1,str2);//把str2链接到str1中,总长度空间大于两个的空间
    
        puts(str1);
    
        puts(str2);
    
        printf("len=%lu
    ",strlen(str1));//计算字符串的长度
    
        printf("len=%lu
    ",strlen(str2));//不包括''
    
        printf("%d
    ",strcmp(str1, str2)) ;

    结果:

     

     字符函数部分:需要导入头文件

    #include <ctype.h>
        char ch='a',ch1='A';
        printf("%d
    ",isalpha(ch));//是否为字母
        printf("%d
    ",isupper(ch));//是否为大写
        printf("%d
    ",islower(ch));//是否为小写
        printf("%d
    ",isdigit(ch));//是否为数字
        
        printf("%c
    ",toupper(ch));//转变为大写
        printf("%C
    ",tolower(ch1));//转变为小写

    字符串大写变小写,小写变大写

        char ch[100],ch1;
        gets(ch);
        int i=0;
        while (ch[i]!='') {
            ch1=ch[i];
            if (isupper(ch1)==1) {
               ch1= tolower(ch1);
            }else{
                ch1=toupper(ch1);
            }
            putchar(ch1);
            i++;
        }
        printf("
    ");

    字符串转为整型或浮点型

    需要导入头文件

    #include <stdlib.h>
      //字符串转
        
        char *chs="11.52";
        printf("chs=%s
    ",chs);
        double d=atof(chs);
        int a=atoi(chs);
        printf("%f
    ",d);
        printf("%d
    ",a);
        
        

    数字转字符串

     int num=1000;
        char chs[100];
        //将num按照%d的格式存储到chs中
        sprintf(chs,"%d",num);
        printf("chs=%s
    ",chs);
        //将字符串按照指定的格式存储
        sprintf(chs, "%10s","asdf");
        printf("chs=%s",chs);

  • 相关阅读:
    sqhhb
    12333
    12

    今日份
    12
    彻底理解 Cookie、Session、Token
    https原理
    12312
    uiower
  • 原文地址:https://www.cnblogs.com/qianLL/p/5088608.html
Copyright © 2011-2022 走看看