C++标准模板(STL) string

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str;
    str = "hello world!";
    string::iterator it = str.begin();//string使用迭代器访问
    for(; it != str.end(); it++)
        cout<<*it<<endl;

    str += "yjy";//+对于string来说是拼接的作用。
    cout<<str<<endl;

    string str2 = "yjy";
    if(str > str2)//在string中,可以直接用<  >= 等来进行比较
        cout<<"str > str2"<<endl;
    else if(str <= str2)
        cout<<"str <= str2"<<endl;

    cout<<"the size of str is "<<str.size()<<endl;//求字符串长度
    cout<<"the size of str2 is "<<str2.length()<<endl;

    str.insert(1, str2);//在str的1号位置插入字符串str2,位置是从0开始计算的。
    cout<<str<<endl;

    str.erase(str.begin()+1, str.begin()+3);//删除str的区间内容
    cout<<str<<endl;

   // str2.clear();//清空字符串内容。
    cout<<str2.size()<<endl;

    cout<<str.substr(0, 3)<<endl;//substr(pos, length)返回pos号位置开始,长度为length的子字符串

    cout<<str<<" "<<str2<<endl;
    cout<<str.find(str2)<<endl;//找出在str中str2第一次出现的位置。

    cout<<str.replace(0, 4, str2)<<endl;//replace(pos, length, str) 从pos位置开始的length长的字符,替换成str2
    return 0;
}
 

发布了84 篇原创文章 · 获赞 26 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/yjysunshine/article/details/88567966
今日推荐