字符串中常用的系统函数(strcat , strcmp , strcpy,strlen )

字符串中常用的系统函数

(strcat 连接, strcmp 比较, strcpy 拷贝,效果相当于赋值,strlen 求有效字符个数)

1、strcat 函数

strcat 函数即字符串连接函数,其一般格式为:
strcat (字符数组名1,字符串数组名2或者字符串)

其原理是将字符数组2的内容拼接到字符数组1的有效字符之后,结果放在字符数组1中,参数1必须是字符数组,因为需要有存储单元存放字符串,参数2即可以是字符数组也可以是字符串。字符数组1应该要足够大,以便接纳连接后的字符数组。

代码演示:

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

int main(){
char a[]="I";   //字符型常量'I'与字符串常量"I"的限制符不同
char b[]="am";
printf("%s\n",a);
strcat(a,b);
printf("%s\n",a);
strcat(a,"happy");
printf("%s\n",a);
return 0;
system("pause");
}

输出:
I
Iam
Iamhappy

Process returned 0 (0x0)   execution time : 0.359 s
Press any key to continue.


2、strcpy 函数
strcpy函数即字符串复制函数。其一般格式为:
strcpy(字符串数组名1,字符串数组名2或者字符串)

strcpy函数要求参数1必须是字符数组,因为需要有存储单元存放字符串,参数2即可以是字符数组也可以是字符串。字符数组1应该要足够大,以便接纳连接后的字符数组。

注意:strcpy函数的作用相当于赋值,将后一个字符串的内容拷贝给前一个字符串时,后一个字符串会将前一个字符串覆盖掉

代码演示:

//strcpy函数
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(){
char a[20]="hello",b[]="hi";
printf("%s\n",a);
strcpy(a,b);
printf("%s\n",a);
strcpy(a,"see you again\n");
printf("%s\n",a);
return 0;
system("pause");
}
输出为:
hello
hi
see you again


Process returned 0 (0x0)   execution time : 0.338 s
Press any key to continue.

3、strcmp函数
strcmp函数即字符串比较函数,其格式为:
strcmp(字符串数组名1或者字符串,字符串数组名2或者字符串)需要注意的是它不能单独使用,需要放到if中去使用。

strcmp函数的作用是将两个字符串自左至右逐个字符比较(按ASCII码值大小比较),直到出现不同的字符或遇到 "\0"为止。
当字符串 1 =字符串 2 时,函数的返回值为0;
当字符串 1>字符串 2 时,函数的返回值为正整数;
当字符串 1 <字符串 2 时,函数的返回值为负整数;

代码演示:

//strcmp函数
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    char a[]="them",b[]="they";
    int x;
    x=strcmp("the",b);
    printf("函数返回值=%d\n",x);
    if(strcmp(a,b)>0)
        printf("字符串a大\n");
    else if(strcmp(a,b)<0)
        printf("字符串b大\n");
    else
        printf("字符串a和b相等\n");
    return 0;
    system("pause");
}

输出为:

函数返回值=-1
字符串b大

Process returned 0 (0x0)   execution time : 0.435 s
Press any key to continue.

4、strlen函数
strlen函数即测试字符串长度函数,其一般格式为:
strlen (字符数组名或者字符串)

strlen函数的作用是统计字符串的有效字符个数,遇见(不包括)第一个 “\0” 时结束,函数的返回值为字符串的有效字符个数。

代码演示:

//strcmp函数
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
    char a[]="good";
    printf("%d,%d\n",strlen(a),strlen("bye"));
    return 0;
    system("pause");
}

输出结果为:
4
3
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值