C语言基础09 字符串 & 结构体

#include <stdio.h>

void main() {
    // 字符串格式
    char a[7];
    char *p =&a;

    // 把a中放入字符--》做成字符串     justin
    //    a[0]='j';
    //    a[1]='u';
    //    a[2]='s';
    //    a[3]='t';
    //    a[4]='i';
    //    a[5]='n';
    //    a[6]='\0';
    //    printf("%s\n",a);

    // 使用指针p 来放入字符
    //    *p='j';
    //    p++;
    //    *p='u';
    //    printf("%s\n",a);

    // 以后反编译后会看到-->做字符串格式化
    sprintf(p,"%c",'j');
    ++p;
    sprintf(p,"%c",'u');
    ++p;
    sprintf(p,"%c",'s');
    p++;
    sprintf(p,"%c",'t');
    p++;
    sprintf(p,"%c",'i');
    p++;
    sprintf(p,"%c",'n');
    p++;
    sprintf(p,"%c",'\0');
    printf("%s\n",a);

}

字符串包含关系

#include <stdio.h>
#include <string.h>

void main() {
    // 字符串包含关系
    char name[] = "justin is handsome";
    // 判断is 是否在字符串重
    char *res = strstr(name, "is");
    if (res) {
        printf("匹配成功,is存在,匹配的位置:%p",res);
    } else {
        printf("is 不存在");
    }


}

字符串复制和字符串相加

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main() {
    // 字符串复制和相加
    char name[]="justin";
    char role[]="teacher";
    // 申请一个 name和role大小的内存空间
    char *s =malloc(strlen(name)+ strlen(role)+1) ;  // 申请一个内存空间,返回指针类型
    strcpy(s,name); // 字符串复制
    strcat(s,role); //把role拼接到s后
    printf(s);

}

结构体

基本使用

# 在c语言中,是用户自己定义的类型,它允许存储不同类型的数据项

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


// 定义一个 Person结构体---》python中所有变量其实都是c语言结构体指针
// 相当于类,只有属性,没有方法
// Person 结构体有名字和年龄
struct Person{
    char name[30];
    int age;
};


void main() {
    // 使用结构体
    struct Person p1={"justin",18};
    printf("名字是:%s,年龄是:%d\n",p1.name,p1.age);

    // 结构体的指针
    struct Person *pointPerson= &p1;
    printf("名字是:%s\n",(*pointPerson).name);
    printf("年龄是:%d\n",pointPerson->age); // 上面的简写形式


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值