C++:标准库类型string

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bqw18744018044/article/details/82141548
  • 头文件

#include <string>
  • 初始化

 string s1;//空字符串
 string s2 = s1;
 string s2(s1);
 string s3(“value”);//直接初始化
 string s3 = “value”;//拷贝初始化,先创建一个临时对象然后赋值给s3
  • 操作

string s("hello world");
    //string的empty()和size()
    if(!s.empty())
        cout<<s.size()<<endl;
    //访问字符串中的字符
    for(int i=0;i<s.size();i++)
        cout<<s[i]<<",";
    cout<<endl;
    //string对象可以使用=、!=、<、<=、>、>=等符号进行比较
    string s1("hello");
    string s2("world");
    if(s1==s2)
        cout<<s1<<endl;
    else
        cout<<s2<<endl;
    //string对象可以通过+进行连接
    cout<<s1+s2<<endl;
    //读取一个单词到s中(s中不包含空格)
    cin>>s;
    cout<<s<<endl;
    //读取一行字符到s中(s中可以包含空格)
    getline(cin,s);
    cout<<s<<endl;
    //不确定行数的读
    while(cin>>s)
        cout<<s<<endl;

猜你喜欢

转载自blog.csdn.net/bqw18744018044/article/details/82141548
今日推荐