标准库string常用方法

来源:互联网 发布:微课制作软件 编辑:程序博客网 时间:2024/06/06 13:14

  • string常用方法
    • 定义及初始化
    • size 和empty操作
    • 操作符
    • 关系操作符
    • 两个string对象相加
    • 支持迭代器
    • inserterase操作
    • substr操作
    • append函数
    • replace函数
    • find操作

string常用方法

定义及初始化

string类型提供 与vector相同的操作,可视为字符容器,与vetor容器不同的是,string容器不支持以栈方式操作容器,在string类型中不能使用front、back和pop_back操作

 string s1;    string s2="hello";    cout<<s2<<endl;

size() 和empty操作

string s1;    string s2="hello";    cout<<s2.size()<<endl;    if(s1.empty()){     cout<<""<<endl;    }

[]操作符

    string s2="hello";    for (int i=0; i<s2.size(); i++) {    cout<<s2[i]<<" "<<endl;     }

关系操作符

如果两个string对象的字符不同,则比较第一个不匹配的字符
如果两个string对象的长度不同,且短的string对象与长的string对象的前面部分相同,则短的string对象小于长的string对象

 string s1 = "hello world";    string s2 = "hello";    string s3 = "hiya";    string s4="hello world";    if(s1 >s2){      cout <<"s1小于s2"<<endl;    }     if(s1<s3) {       cout<<"s1小于s3"<<endl;    }    if(s1 == s4) {       cout<<"s1等于s4"<<endl;    }

两个string对象相加

string对象可以通过加法被定义为链接,使用+或+=连接起来

string s1 = "hello world ";    string s2 = "hello";    string s3 =s1 + s2;    cout<<s3<<endl;

支持迭代器

  string s1 = "hello world ";    string s2 = "hello";    string s3 =s1 + s2;    string::iterator iter=s3.begin();    while(iter != s3.end()) {      cout<<*iter++<<endl;    }

insert、erase操作

string s3 = "hello world ";    string::iterator iter=s3.begin();    s3.insert(s3.begin(),3,'c');    while(iter!=s3.end()){      cout<<*iter++<<endl;    }    s3.erase(s3.begin(),s3.begin()+5);    iter=s3.begin();    while(iter!=s3.end()){      cout<<*iter++<<endl;    }

只适用于string类型的操作

substr操作

string s3 = "hello world ";    cout<<s3.substr(1,3)<<endl;

append函数

用于修改string对象

string s3 = "hello world ";    s3.append("facebook");    cout<<s3<<endl;

replace函数

I.s.replace(pos,len,args). 删除s中从下标pos开始开始的len个字符

 string s3 = "hello world "; cout<<s3.replace(0,2,"ccc")<<endl;

II. s.replace(b,e,args),删除迭代器b和e范围内所有的字符,用args替换

 string s3 = "hello world ";    s3.replace(s3.begin(),s3.begin()+3,"facebook");    cout<<s3<<endl;

find操作

string s3 = "hello world ";    string::size_type pos1=s3.find("llo");    cout<<pos1<<endl;
0 0
原创粉丝点击