字符串相关操作函数

该博客介绍了C语言中字符串相关操作函数,使用这些函数需先添加string.h头文件。详细阐述了strcpy、strcat、strlen和strcmp函数的功能,如strcpy和strcat用于字符串追加,strlen计算字符串长度,strcmp比较字符串大小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串相关操作函数

使用字符串相关操作函数要先添加string.h头文件

1、strcpy(char dest[], char src[])

功能:把src数组’\0’之前的字符串追加到dest字符串后,若是dest中有’\0’, 会把dest中的’\0’给覆盖掉,然后新组成的dest字符串会重新添加’\0’

#include<stdio.h>
#include<string.h>
int  main(){
char dest[20]={"hello"};
strcpy(dest,"hi");
for(int i=0;dest[i]!='\0';i++){

	printf("%c\n",dest[i]);
}



}

输出结果:

h
i

2、strcat(char dest[], char src[])

功能:把src数组’\0’之前的字符串追加到dest字符串后,若是dest中有’\0’,
会把dest中的’\0’给覆盖掉,然后新组成的dest字符串会重新添加’\0’

从键盘输入一串字符,将这串字符拼接到hello的后面

#include<stdio.h>
#include<string.h>
int  main(){
char dest[20]={"hello"};
char src[20];
printf("please enter string\n");
gets(src);
strcat(dest,src);
for(int i=0;dest[i]!='\0';i++){

	printf("%c\n",dest[i]);
}



}

输出结果:

h
e
l
l
o
w
o
r
l
d
li

3、int strlen(const char s[])

功能:计算s数组中第一个’\0’前字符的个数,并返回

#include<stdio.h>
#include<string.h>
int  main(){
char dest[20]={"hello"};

printf("strlen=%ld\n",strlen(dest));
printf("sizeof=%ld\n",sizeof(dest)/sizeof(dest[0]));
}

输出结果:

strlen=5
sizeof=20

strlen求的是’\0’前字符的个数,sizeof求得是数组的内存大小

4、int strcmp(char s1[], char s2[]);

功能: 对s1和s2字符串中的每个字符逐个比较, 若是s1中某个字符>s2中的某个字符,则返回大于0的数, 若是s1中某个字符<s2中的某个字符,则返回小于0的数, 若是当前s1和s2的字符相等,则比较后一个字符。若是完全相等,返回0

注:在gcc的32bit编译器下,返回如下值:若是s1 > s2 ,返回1若是s1 == s2, 返回0若是s1 < s2 ,返回-1char,在64bit下,返回值是s1的ASCII码-s2的ASCII码

#include<stdio.h>
#include<string.h>
int  main(){
char dest[20];
char src[20];
printf("please enter dest:\n");
gets(dest);
printf("please enter src:\n");
gets(src);
int result=strcmp(dest,src);
if(result>0){
printf("dest>src");
}
else if(result==0){
printf("dest=src");
}
else {

printf("dest<src");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值