C 和C++ 字符串比较

C++ 提供了以下两种类型的字符串表示形式:

  • C 风格字符串

  • C++ 引入的 string 类类型

。字符串实际上是使用 null 字符 '' 终止的一维字符数组。因此,一个以 null 结尾的字符串,包含了组成字符串的字符。

由于在数组的末尾存储了空字符,所以字符数组的大小比单词 "Hello" 的字符数多一个

char greeting[6] = {'H', 'e', 'l', 'l', 'o', ''};

依据数组初始化规则,您可以把上面的语句写成以下语句:

char greeting[] = "Hello";

其实,您不需要把 null 字符放在字符串常量的末尾。C++ 编译器会在初始化数组时,自动把 '' 放在字符串的末尾

C++ 中有大量的函数用来操作以 null 结尾的字符串

strcpy(s1, s2);
复制字符串 s2 到字符串 s1。

strcat(s1, s2);
连接字符串 s2 到字符串 s1 的末尾。

strlen(s1);
返回字符串 s1 的长度。

strcmp(s1, s2);
如果 s1 和 s2 是相同的,则返回 0;如果 s1<s2 则返回值小于 0;如果 s1>s2 则返回值大于 0。

strchr(s1, ch);
返回一个指针,指向字符串 s1 中字符 ch 的第一次出现的位置。

strstr(s1, s2);
返回一个指针,指向字符串 s1 中字符串 s2 的第一次出现的位置。

#include<cstring>
using namespace std;
int main(){

char str[]={'a','b','c','d'};
char str1[]={'a','b','c','d',''};
#include<iostream>
#include<cstring>
using namespace std;
int main(){

char str[]={'a','b','c','d'};
char str1[]={'a','b','c','d',''};
char str2[strlen(str)];

strcpy(str2,str);
cout<<str2;
cout<<str<<endl;
cout<<str1;



return 0;
}

image.png

C++ 标准库提供了 string 类类型,

#include<iostream>
#include<string>
using namespace std;
int main(){
string str="hello";
string str2="world";
string str3;

str3=str;
cout<<"将str赋值给str3"<<str3<<endl;
cout<<"拼接str和str2"<<str+str2<<endl;
cout<<"str3的长度"<<str3.size();

return 0;
}

image.png

注意字符串str3的长度为5 这是因为不同于C语言的字符串 这里没有 null字符

原文地址:https://www.cnblogs.com/webcyh/p/11264206.html