C++的string数据类型
一、问题引入
在C中是没有字符串数据类型的,字符串通常是放在字符数组中,在末尾添加 \0
来表示字符串。
但是在C++中,直接给搞出了一种新的数据类型 即 string
二、解决过程
- char 与 string
#include <iostream>
using namespace std;
int main(void)
{
char str_1[100] = {0};
string str_2;
cout<<"Please input the 1st word: "<<endl;
cin>>str_1;
cout<<"Please input the 2nd word: "<<endl;
cin>>str_2;
cout<<"Now we receive your 2 words:"<<endl;
cout<<str_1<<endl;
cout<<str_2<<endl;
return 0;
}
💡 运行结果
- string的特性
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
string str;
cout<<"Please input a line string: "<<endl;
getline(cin, str);
// string strlen()
cout<<"str's size "<<str.size()<<endl;
// string strcat()
str = str + " world";
cout<<str<<endl;
// string strcpy()
str = "welcome to China";
cout<<str<<endl;
// string sprintf()
str.append(", we using ChatGPT.");
cout<<str<<endl;
return 0;
}
💡 运行结果
三、反思总结
直接使用string数据类型无需手动检测 \0
结束标志。其实string准确的说是一个字符串类,可以使用它的类方法等等。
ISO/ANSI C++98标准通过添加string类扩展了C++库,因此现在可以使用string类型的变量(C++中叫 对象)而不是字符数组来存储字符串。
扩展知识
string对象可以作为结构体中的成员
struct Student
{
std::string name;
std::string sex;
int age;
};
四、参考引用
C++ Primer Plus