Loading

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

作者:caojun97

出处:https://www.cnblogs.com/caojun97/p/17296868.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   eiSouthBoy  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu