常用字符串函数

注意:使用字符串函数时,需要添加头文件#include <string.h>

编译器:DEV C++

一、统计字符串长度函数      strlen(串首地址)  /*解释串首地址:数组的名*/

作用:计算有效字符个数

#include <stdio.h>
#include <string.h>
int main(void)
{
   char s[10]="china";
   printf("%d",strlen(s));
}

 输出结果  (无符号整数):5   /*china字符串长度为5*/

二、字符串拷贝函数      strcpy(串1首地址符,串2首地址符)

作用:将串2连同结束符一起从串1的0下标位置开始覆盖

例1、简单的两个字符串覆盖

#include <stdio.h>
#include <string.h>
int main(void)
{
   char s[10]="china";
   char t[10]="123";
   strcpy(s,t);/*s为串1首地址,t为串2首地址*/
   puts(s);
}

 输出结果:123(“china”被“123”所覆盖)

例2、字符串间交换

#include <stdio.h>
#include <string.h>
int main(void)
{
   char s[10]="china";
   char t[10]="123";
   char k[10]  ; /*空数组做中间值*/
   strcpy(k,s); /*k被s覆盖*/
   strcpy(s,t); /*s被t覆盖*/
   srtcpy(t,k); /*t被k覆盖*/
   puts(s);
   puts(t);
}

输出结果:123 china

 三、字符串拼接        strcat(串1首地址符,串2首地址符)

作用:将串2连同结束符一起从串1的结束符位置开始向后覆盖

#include <stdio.h>
#include <string.h>
int main(void)
{
   char s[10]="china";
   char t[10]="123";
   strcat(s,t); /*调用strcat函数*/
   puts(s);
}

输出结果:china123

 四、字符串的比较      strcmp(串1首地址符,串2首地址符)

作用:将两个串从下标0位置开始并对齐,两两进行比较首字符的ASCII值,若要相同,则一次向后顺延比较,知道比出大小;一旦不同,则停止后面的比较。

输出值的几种情况:

(1)、串1>串2时---->1

(2)、串1<串2时---->-1

(3)、串1=串2时----->0

#include <stdio.h>
#include <string.h>
int main(void)
{
   char s[10]="china";
   char t[10]="123";
   
   if(strcmp(s,t)>0)
      printf("大于");
	 else
	   printf("小于"); 
}

输出结果:大于

五、字符串字母大小写转换函数      注:不适用于指针变量

a、大写转小写  strlwr(数组首地址)

b、小写转大写  sreupr(数组首地址)

#include <stdio.h>
#include <string.h>
int main(void)
{
   char s[10]="china";
    strupr(s);
    puts(s);
}

输出结果:CHINA

大写转小写

#include <stdio.h>
#include <string.h>
int main(void)
{
   char s[10]="CHINA";
    strlwr(s);
    puts(s);
}

 输出结果:china

 六、字符串倒置函数     strrev(数组首地址) 

#include <stdio.h>
#include <string.h>
int main(void)
{
   char s[10]="abcde";
    strrev(s);
    puts(s);
}

输出结果:edcba

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值