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

Posted xing-ting

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常用的字符串函数的几种操作相关的知识,希望对你有一定的参考价值。

声明 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. ",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. ",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. ");
else if(value < 0)
printf("a>b. ");
else if(value > 0)
printf("a<b. ");
else
{
printf("wrong. ");
}

return 0;
}

打印结果:a<b.

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

int main(void)
{

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

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

return 0;
}

打印结果:value = 6.

































































以上是关于常用的字符串函数的几种操作的主要内容,如果未能解决你的问题,请参考以下文章

吐血整理Python 常用的几种高阶函数和简单的迭代函数

javascript中常用操作字符串的几种方法charAt()indexOf()slice()substr()

函数返回值为字符串的几种写法

MySQL字符串处理函数的几种常见用法

函数的几种常用形式

MySQL常用的数据类型及函数_20160920