字符串复制,拼接,比较大小函数

1. 字符串比较大小函数:strcmp():

这是一个字符串比较函数,作用是比较两个字符串。函数原型:

cpp 复制代码
int strcmp(const char *str1, const char *str2)

其中 str1 和 str2 是要进行比较的字符串。

如果 str1 < str2,则返回值 < 0;

如果 str1`== str2,则返回值 == 0;

如果 str1 > str2,则返回值 > 0。

字符串比较是按照 ASCII 值进行的。

cpp 复制代码
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    
    int result = strcmp(str1, str2);
    
    if (result < 0) {
        printf("str1 is less than str2\n");
    } else if (result == 0) {
        printf("str1 is equal to str2\n");
    } else {
        printf("str1 is greater than str2\n");
    }
    
    return 0;
}

输出结果:

cpp 复制代码
str1 is less than str2

2. 字符串复制函数strcpy():

这是一个字符串复制函数,作用是将源字符串(含有'\0')复制到目标字符串中。函数原型:

cpp 复制代码
char *strcpy(char *dest, const char *src)

,其中 dest 和 src 分别是目标字符串和源字符串。

cpp 复制代码
#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "Hello, World!";
    char dest[50];
    
    strcpy(dest, src);
    
    printf("Source string : %s\n", src);
    printf("Destination string : %s\n", dest);
    
    return 0;
}

输出结果:

cpp 复制代码
Source string : Hello, World!
Destination string : Hello, World!

3. 字符串拼接函数strcat():

这是一个字符串连接函数,作用是将源字符串(除'\0'外)追加到目标字符串后,返回目标字符串。函数原型:

cpp 复制代码
char *strcat(char *dest, const char *src)

,其中 dest和 src分别是目标字符串和源字符串。

cpp 复制代码
#include <stdio.h>
#include <string.h>

int main() {
    char dest[50] = "Hello, ";
    char src[] = "World!";
    
    strcat(dest, src);
    
    printf("After concatenation: %s\n", dest);
    
    return 0;
}

输出结果:

cpp 复制代码
After concatenation: Hello,World!
相关推荐
DuHz5 分钟前
基于频率分集阵列的MIMO雷达联合距离角度估计——论文阅读
论文阅读·算法·汽车·信息与通信·毫米波雷达
INGNIGHT27 分钟前
单词搜索 II · Word Search II
数据结构·c++·算法
黄卷青灯771 小时前
标定系数为什么会存储在相机模组里面,在标定的时候,算法是在割草机的X3板上运行的啊?
数码相机·算法·相机内参
螺丝钉的扭矩一瞬间产生高能蛋白1 小时前
PID算法基础知识
算法
HVACoder2 小时前
复习下线性代数,使用向量平移拼接两段线
c++·线性代数·算法
爱coding的橙子2 小时前
每日算法刷题Day77:10.22:leetcode 二叉树bfs18道题,用时3h
算法·leetcode·职场和发展
Swift社区2 小时前
LeetCode 404:左叶子之和(Sum of Left Leaves)
算法·leetcode·职场和发展
南枝异客2 小时前
查找算法-顺序查找
python·算法
QuantumLeap丶2 小时前
《数据结构:从0到1》-06-单链表&双链表
数据结构·算法
李牧九丶3 小时前
从零学算法59
算法