常用的字符串函数的几种操作

声明 a是destination的首地址,b是source的地址

(1)strcpy
作用:strcpy的作用是把source的b复制到destination中的a
使用方式:strcpy(a,b)
使用示例程序如下:

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

int main(void)
{
char array_test[10] = {0};
char *dest_str = "hello!";
strcpy(array_test,dest_str);

printf("array_test = %s.\n",array_test);

return 0;
}
打印结果:array_test = hello!

(2)strncpy
作用:strncpy的作用是把source的b中的n个字符复制到destination中的b
使用方式:strcpy(a,b,n)
使用示例程序如下:
#include<stdio.h>
#include<string.h>

int main(void)
{
char array_test[10] = {0};
char *dest_str = "hello!";
strncpy(array_test,dest_str,2);

printf("array_test = %s.\n",array_test);

return 0;
}

打印结果:array_test = he.
(3)strcmp
作用:strcmp(a,b)的作用是把a和b进行比对,如果a==b则返回一个等于0的值,如果a>b则返回一个大于0的值,如果a<b则返回一个小于0的值。
使用方法:strcmp(a,b)
使用示例程序:
#include<stdio.h>
#include<string.h>

int main(void)
{


char *a = "hELLO!";
char *b = "Hello!";

int value = strcmp(a,b);
if(value == 0)
printf("a==b.\n");
else if(value < 0)
printf("a>b.\n");
else if(value > 0)
printf("a<b.\n");
else
{
printf("wrong.\n");
}

return 0;
}

打印结果:a<b.

(4)strlen
作用:计算字符串的长度
使用方法:strlen(b)
使用示例程序:
#include<stdio.h>
#include<string.h>

扫描二维码关注公众号,回复: 3573166 查看本文章

int main(void)
{

char *b = "afjoaf";
int value = strlen(b);

printf("value = %d.\n",value);

return 0;
}

打印结果:value = 6.

猜你喜欢

转载自www.cnblogs.com/xing-ting/p/9785118.html