天天看点

C++中常用的字符串函数字符串连接函数 strcat()字符串复制函数 strcpy()字符串比较函数 strcmp()

       C++语言提供了比C语言更丰富的字符串处理功能。它可以在字符串上经行输入,输出,合并,修改,比较,转换,复制,搜索等操作。使用这些现成的功能可以大大减少我们的编程的负担。

       输入和输出的字符串函数,如printf,puts,cout,scanf,gets,cout等,在使用时应包含头文件cstdio,并使用其他字符串函数包含头文件cstring。

        cstring是一个专门用于处理字符串的头文件。它包含许多字符串处理函数。由于篇幅限制,本节只能解释一些常见的内容。

字符串连接函数 strcat()

strcat 就是 string catenate 的缩写,意思为把两个字符串拼在一起,其格式为:

strcat(Str1, Str2);

Str1、Str2 为需要拼接的字符串。

strcat() 将把 Str2 连接到 Str1 后面,并删除原来 Str1 最后的结束标志\0。这意味着,Str1 必须足够长,要能够同时容纳 Str1 和 Str2,否则字符数组会越界(超出字符串范围)。

strcat() 的返回值为 Str1 的地址。

这是一个简单的演示:

#include <cstdio>
#include <cstring>
int main(){
    char str1[100]="The URL is ";
    char str2[60];
    cout<<"Input a URL: ";
    gets(str2);
    strcat(str1, str2);
    puts(str1);
    return 0;
}
           

运行结果:

Input a URL: https://blog.yunhei.org/index.php/archives/13/↙(输入)

The URL is https://blog.yunhei.org/index.php/archives/13/

字符串复制函数 strcpy()

strcpy 是 string copy 的缩写,意思是字符串复制,也即将字符串从一个地方复制到另外一个地方,语法格式为:

strcat(Str1, Str2);

strcpy() 会把 Str2 中的字符串拷贝到 Str1 中,字符串结束标志\0也一同复制。下面是一个简单的演示:

#include <cstdio>
#include <cstring>
int main(){
    char str1[50] = "云黑系统";
    char str2[50] = "https://yunhei.org/";
    strcpy(str1, str2);
    printf("str1: %s\n", str1);
 
    return 0;
}
           

运行结果:

str1: https://yunhei.org/

你看,将 str2 复制到 str1 后,str1 中原来的内容就被覆盖了。

另外,strcpy() 要求 Str1 要有足够长的长度,否则不能全部装入所复制的字符串。

字符串比较函数 strcmp()

strcmp 是 string compare 的缩写,表示字符串比较。语法是:

strcmp(Str1, Str2);

Str1 和 Str2 是两个需要比较的字符串。

字符本身没有大小,strcmp()比较字符的ASCII值。

strcmp()开始比较两个字符串的第0个字符。如果它们相等,它们会继续比较下一个字符,直到它们遇到不同的字符或字符串的末尾。

返回值:如果 Str1 和 Str2 相同,则返回0;如果 Str1 大于 Str2,则返回大于 0 的值;若 Str1 小于 Str2,则返回小于0 的值。

比较4组字符串:

#include <cstdio>
#include <cstring>
int main(){
    char str1[] = "aBcDeF";
    char str2[] = "AbCdEf";
    char str3[] = "aacdef";
    char str4[] = "aBcDeF";
    printf("a VS b: %d\n", strcmp(a, b));
    printf("a VS c: %d\n", strcmp(a, c));
    printf("a VS d: %d\n", strcmp(a, d));
 
    return 0;
}
           

运行结果:

str1 VS str2: 32

str1 VS str3: -31

str1 VS str4: 0

原文链接:https://blog.csdn.net/qq_41510854/article/details/95180798

继续阅读