C语言字符串、结构体

目录

字符串

1.常用字符串函数

1.1example

结构体

 1.定义结构体

1.1格式:

1.2结构方式:

 2.访问结构成员


字符串

1.常用字符串函数

函数目的(作用)
strcpy(s1,s2);

复制字符串s2到字符串s1。

strcat(s1,s2);

连接字符串s2到字符串s1。

strlen(s1);返回字符串s1长度。
strcmp(s1,s2);如果s1,s2是相同的,则返回0;如果s1<s2返回小于0;如果s1>s2则返回大于0。
strchr(s1,ch);返回一个指针,指向字符s1中字符ch的第一次出现位置。
strstr(s1,s2);返回一个指针,指向字符串s1中字符串s2的第一次出现的位置。

1.1example

#include<stdio.h>
#include<string.h>
int main(){
      char str1[20]="hanx";
      char str2[20]="blog";
      char str3[20];
      int len;
      strcpy(str3,str1);//复制str1到str3
      printf("strcpy(str3,str1):%s\n",str3);
      strcat(str1,str2);
      printf("strcat(str1, str2):%s\n", str1);//连接str1和str2
      len = strlen(str1);
      printf("strlen(str1):%d\n", len);//连接后,str1总长度;
      return 0;
  }

执行结果:

strcpy(str3,str1):hanx
strcat(str1, str2):hanxblog
strlen(str1):8

结构体

 1.定义结构体

结构体定义由struct和结构体名(自行定义)组成。

1.1格式:

struct tag{ 
    member-list
    member-list 
    member-list  
    ...

 }variable-list;
//tag 结构体标签。
//member-list 标准的变量定义 eg:int i;或者 double m;
//variable-list 结构变量,定义在结构末尾,最后一个分号之前,可以指定一个或多个结构变量

注:结构体中的数据成员可以是基本数据类型(int、float、char等),也可以是其他结构体类型、指针类型等。

1.2结构方式:

//tag 结构体标签。
//member-list 标准的变量定义 eg:int i;或者 double m;
//variable-list 结构变量,定义在结构末尾,最后一个分号之前,可以指定一个或多个结构变量.

  • 在一般情况下,tag、member-list、variable-list 这 3 部分至少要出现 2 个。

(tag:People)

struct People{
       char name[50];
       char id[50];
       int age;

}people;

实例:

#include <stdio.h>
 
struct People
{
   char  name[50];
   char  id[50];
   int   age;
} people = {"李华", "112233", 18};
 
int main()
{
    printf("name : %s\nid: %s\nage:%d\n", people.name,people.id,people.age);
}

运行结果:

name : 李华
id: 112233
age:18

 2.访问结构成员

#include <stdio.h>
#include <string.h>
 
struct People
{
   char  name[50];
   char  id[50];
   int   age;
};
 
int main( )
{
   struct People people1;        /* 声明 people1,类型为 People */
   struct People people2;        /* 声明 people2,类型为 People */
 
   /* people1 详述 */
   strcpy( people1.name, "Lihua");
   strcpy( people1.id, "112233"); 
   people1.age=18;
 
   /* People2 详述 */
   strcpy( people2.name, "Jane");
   strcpy( people2.id, "445566"); 
   people2.age=18;
 
   /* 输出 People1 信息 */
   printf("People 1 name : %s\n", people1.name);
   printf("People 1 id : %s\n", people1.id);
   printf("People 1 age: %d\n", people1.age);
 
   /* 输出 People2 信息 */
   printf("People 2 name : %s\n", people2.name);
   printf("People 2 id : %s\n", people2.id);
   printf("People 2 age: %d\n", people2.age);
  
   return 0;
}

运行结果:

People 1 name : Lihua
People 1 id : 112233
People 1 age: 18
People 2 name : Jane
People 2 id : 445566
People 2 age: 18

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值