字符串和字符函数


#include <stdio.h>
#define MSG "You must have many talents.Tell me some."//一个符号字符串常量
#define LIM 5
#define LINELEN 81      //最大字符串长度+1
int main()
{
    char name[LINELEN];
    char talents[LINELEN];
    int i;
    //初始化一个大小已确定的char数组
    const char m1[40] = "Limit yourself to one line`s worth.";
    //让编译器计算数组大小
    const char m2[] = "If you can`t think of anything,fake it.";
    //初始化一个指向字符串的指针
    const char *m3 = "\nEnough about me - what`s your name?";
    //初始化一个字符串指针的数组
    const char *mytal[LIM] = {
        "Adding numbers swiftly",
        "Multiplying accurately",
        "Stashing data",
        "Following instructions to the letter",
        "Understanding the C language"
    };
    for(i=0;i<LIM;i++)
        puts(mytal[i]);
    puts(m3);
    gets(name);
    printf("Well,%s,%s\n",name,MSG);
    printf("%s\n%s\n",m1,m2);
    gets(talents);
    printf("%s\n",name);
    return 0;
}

数组与指针

指针方式 char *head = "weqwqeqeqewqeweq";

head 变量

数组方式 char heart[] ="weqwqeqeqewqeweq";

heart 为常量

都可以使用数组符号

head[1]

heart[1]

都可以使用指针加法

*(head+1)

*(heart+1)

只有指针可以使用增量运算(++,--)

head++

//赋值(赋值语句左边必须是变量)

head = heart //指针指向数组 合法

heart = head//非法(heart不是变量是常量)

建议初始化一个指向字符串的指针时使用const修饰符,防止非法操作

const char *p1 ="dssada";


二维数组和指针数组的区别

//指针数组(保存的其实是指针地址,字符串本身不存在数组内)

const char *mytal[LIM] = { "Adding numbers swiftly",

 "Multiplying accurately", "Stashing data", 

 "Following instructions to the letter", "Understanding the C language" };

//二维数组(字符串本身存在数组内)

char mytal_2[LIM][LINLIM]


区别

mytal     指针数组建立的是一个不规则(ragged)的数组,每一行长度由初始化的字符串决定(不浪费空间)

mytal_2  二维数组建立了一个所有行的长度都相同的矩形(rectangular)


#include <stdio.h>
int main(void)
{
    char str1[] = "qazwsxedc";
    char str2[] = "123456789";
    char *a1 = str1;
    char *a2 = str2;
    *a1++ = *a2++;//先赋值后++两边都是
    ++*a1 = ++*a2;//先++再赋值两边都是
    puts(str1);
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值