C中常用字符串处理函数

1)字符串输出函数

puts(字符数组名);

功能:把字符数组中的字符串输出到显示器。

例子:

#include <stdio.h>

void main()
{
char c[]="hello world\n";
puts(c);
}


2)字符串输入函数

gets(字符数组名)

功能:从标准输入设备上输入一个字符串

例子:

#include <stdio.h>


int main()
{
char st[15];
printf("input string:");
gets(st);
puts(st);


return 0;
}


3)字符串连接函数

strcat(字符数组名1,字符数组名2);

功能:把字符数组2中的字符串连接到 字符数组1中字符串的后面,并删除字符串1后的结束标志‘\0’,函数的返回值是字符数组1的首地址。

例子:

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


int main()
{
static char st1[30]="My name is:";
char st2[10];
printf("input your name:");
gets(st2);
strcat(st1, st2);
puts(st1);


return 0;
}


4) 字符串拷贝函数

strcpy(字符数组名1,字符数组名2);

功能:把字符数组2中的字符串复制到 字符数组1中,字符串1后的结束标志‘\0’也一同复制,字符数组2也可以是一个字符串常量,这时相当于把一个字符串赋给一个字符数组,

例子:

#include <stdio.h>
#include <string.h>
int main()
{
char st1[15], st2[]="C language";
strcpy(st1, st2);
puts(st1);

return 0;
}


5) 字符串比较函数

strcmp(字符数组名1,字符数组名2)

功能:按ASCII码值的大小逐个比较两个字符串数组中的各个字符,直到出现不同的字符或遇到'\0'为止,函数的返回值有三种情况:

1)字符串1=字符串2 返回值为0;

2) 字符串1 > 字符串2,返回值为以正整数

3) 字符串1< 字符串2,返回值为一负整数。

例子:

#include <stdio.h>
#include <string.h>
int main()
{
int k;
static char st1[15], st2[] = "abc";
printf("input a string:");
gets(st1);


k = strcmp(st1, st2);
if(k == 0) printf("st1 = st2\n");
if(k > 0) printf("st1 > st2\n");
if(k < 0) printf("st1 < st2\n");


return 0;
}


6) 求字符串长度函数

strlen(字符数组名)

功能:求字符串的实际长度(不含字符串结束标志'\0'),并作为函数返回值,

例子:

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


int main()
{
int k;
static char str[]="abcde";
k=strlen(str);
printf("The length of the string is %d\n", k);


return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值