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

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!
相关推荐
limingade2 小时前
手机实时提取SIM卡打电话的信令和声音-新的篇章(一、可行的方案探讨)
物联网·算法·智能手机·数据分析·信息与通信
jiao000015 小时前
数据结构——队列
c语言·数据结构·算法
迷迭所归处6 小时前
C++ —— 关于vector
开发语言·c++·算法
leon6256 小时前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
CV工程师小林6 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
Navigator_Z7 小时前
数据结构C //线性表(链表)ADT结构及相关函数
c语言·数据结构·算法·链表
Aic山鱼7 小时前
【如何高效学习数据结构:构建编程的坚实基石】
数据结构·学习·算法
天玑y7 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
sjsjs117 小时前
【数据结构-一维差分】力扣1893. 检查是否区域内所有整数都被覆盖
数据结构·算法·leetcode
redcocal7 小时前
地平线秋招
python·嵌入式硬件·算法·fpga开发·求职招聘