【C语言】一些常用的字符串函数--学习笔记

1、strcat(buf, text);

作用:用于连接两个字符串
用例, 连接buf+text:

#include <stdio.h>
#include <string.h>
 
int main ()
{
   char src[50], dest[50];
 
   strcpy(src,  "This is source");
   strcpy(dest, "This is destination");
 
   strcat(dest, src);
 
   printf("最终的目标字符串: |%s|", dest);
   
   return(0);
}

2、strcpy()

strcpy()函数是C语言中的一个复制字符串的库函数
用例, 将c复制到a:

#include<string.h>
#include <stdio.h>
void main()
{
	char a[20], c[] = "I am a teacher!";
	strcpy(a, c);
	printf(" c=%s\n", c);
	printf(" a=%s\n", a);

}

3、sprintf()

sprintf()函数是将内容打印进buffer[]
用例:

#include<string.h>
#include <stdio.h>
int main()
{
    int ddd=666;
    char *buffer=NULL;    
    if((buffer = (char *)malloc(80*sizeof(char)))==NULL)
    {
        printf("malloc error\n");
    }
    sprintf(buffer, "The value of ddd = %d", ddd);//The value of ddd = 666
    printf("%s\n",buffer);
    free(buffer);
    buffer=NULL;
    return 0;
}

4、strstr()

查找第一次出现“IPD”标志的位置,
比如:strstr(buff, “IPD,”); //在buf中搜索“IPD”头

#include <stdio.h>
#include <string.h>
int main()
{
   const char buff[20] = "WWW.IPD:hello";
   const char need[10] = "IPD";
   char *ret;
 
   ret = strstr(haystack, need);
 
   printf("子字符串是: %s\n", ret);
   
   return(0);
}

该函数返回在 buff 中第一次出现 need 字符串的位置,如果未找到则返回 null

5、strchr()

strchr() 函数搜索字符串在另一字符串中的第一次出现位置
比如:strchr(buff, ‘:’); //在buff中找到’:’

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

int main ()
{
   const char buff[] = "IPD:liangwwff ";
   const char ch = ':';
   char *ret;

   ret = strchr(buff, ch);

   printf("|%c| 之后的字符串是 - |%s|\n", ch, ret);
   
   return(0);
}

该函数返回在字符串 str 中第一次出现字符 c 的位置,如果未找到该字符则返回 NULL。

6、strlen()

strlen() 函数用来求字符串的长度(包含多少个字符)

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

void main()
{
    char str[100] = { 0 };
    size_t len;
    gets(str);
    len = strlen(str);
    printf("Length: %d\n", len);
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值