您当前的位置:首页 > 计算机 > 编程开发 > C语言

C语言字符串操作范例

时间:01-03来源:作者:点击数:

简单的字符串操作,包括输入输出、求长度、字符串比较和复制等。

#include <stdio.h>
#define MAXBUFF 128
int main(void) {
    char c[] = "012345";
    char line[MAXBUFF];
    int lcv;
    int cmp;
    printf("sizeof(c)= %d\n", sizeof(c));
    printf("sizeof(line)= %d\n", sizeof(line));
    for (lcv=0; lcv<=strlen(c); lcv++)
        printf("c[lcv]= %d = %c\n",c[lcv],c[lcv]);
    printf("Please enter a string : ");
    scanf("%s",line);
    printf("strlen(line) = %d\n", strlen(line));
    printf("line = [%s]\n",line);
    cmp = strcmp(c,line);
    if(cmp<0)
        printf("%s is less than %s\n", c, line);
    else if (c==0)
        printf("%s is equal to %s\n", c, line);
    else
        printf("%s is greater than %s\n", c, line);
    strcpy(line,c);  // 将字符串 c 复制到 line
    cmp = strcmp(c,line);
    if(cmp<0)
        printf("%s is less than %s\n", c, line);
    else if (cmp==0)
        printf("%s is equal to %s\n", c, line);
    else
        printf("%s is greater than %s\n", c, line);
}

输出结果:

sizeof(c)= 7
sizeof(line)= 128
c[lcv]= 48 = 0
c[lcv]= 49 = 1
c[lcv]= 50 = 2
c[lcv]= 51 = 3
c[lcv]= 52 = 4
c[lcv]= 53 = 5
c[lcv]= 0 =
Please enter a string : roses are red
strlen(line) = 5
line = [roses]
012345 is less than roses
012345 is equal to 012345
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门