一丶strcpy和strncpy
1.strcpy
#include <string.h>
char *strcpy(char *dest, const char *src);
功能:实现字符串复制
参数:char *dest:目标字符串首地址
const char *src:原字符串首地址
返回值:目标字符串首地址
注意:复制包括\0
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char s[32] = "hello";
char c[32] = "wor";
strcpy(s, c); //将数组c复制到数组s当中
printf("%s\n", s); //wor,由于会把\0复制进去,所以s数组中复制完wor就会停止
return 0;
}
2.strncpy
char *strncpy(char *dest, const char *src, size_t n);
功能:实现字符串复制
参数:char *dest:目标字符串首地址
const char *src:原字符串首地址
size_t n:复制字符个数
返回值:目标字符串首地址
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char s[32] = "hello";
char c[32] = "world";
strncpy(s, c, 3); // 由于复制3个字符,所以是把wor复制过去
printf("%s\n", s); // worlo
return 0;
}
二丶strlen
#include <string.h>
size_t strlen(const char *s);
功能:计算字符串的实际长度
参数:s:字符串首地址
返回值:字符串的实际长度
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char buf[] = {"hello world"};
int a = strlen(buf); //定义一个整型变量接受strlen
printf("%d",a); //a=11,不包括\0
return 0;
}
三丶strcat和strncat
1.strcat
#include <string.h> char *strcat(char *dest, const char *src);
功能:用于字符串拼接,将原字符串拼接到目标字符串的后面
参数:char *dest:目标字符串首地址
const char *src:原字符串首地址
返回值:目标字符串首地址
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char s1[32] = "hello";
char *s2 = "world";
strcat(s1, s2);
printf("%s\n", s1); // helloworld
return 0;
}
2.strncat
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char s1[32] = "hello";
char *s2 = "world";
strncat(s1, s2, 3); //将s2的前三个字符拼接到s1中
printf("%s\n", s1); // hellowor
return 0;
}
四丶strcmp
#include <string.h> int strcmp(const char *s1, const char *s2);
功能:用于字符串比较
参数:s1、s2是字符串首地址
返回值:从字符串首个字符开始比较字符的ASCII的大小,如果相等继续向后判断
正数 s1 > s2
0 s1 == s2
负数 s1 < s2
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char s1[] = "hello";
char s2[] = "helloworld";
char *s3 = "hqyj";
char *s4 = "nihaoshijie";
// int ret = strcmp(s1, s2); // s1 < s2 负数
// int ret = strcmp(s1, s3); // s1 < s3 负数
// int ret = strcmp(s2, s4); // s2 < s4 负数
int ret = strcmp(s3, s2); // s3 > s2 正数
printf("%d\n", ret);
return 0;
}
标签:const,string,day9,int,s2,s1,嵌入式,char,include
From: https://blog.csdn.net/qq_64136247/article/details/140896734