9.5 Additional string Operation(额外的字符串操作)

9.5.1其他方法去构造string

1.我们能够通过 substr 选择开始位置和数量

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string str1 = "helloworld!";
    string str2 = str1.substr(5, 6);//str1[5]开始复制,长度6
  //string str2 = str1.substr(5);从str1[5]开始到最后,5 < str1.size()
cout << str2 << endl; system("PAUSE"); return 0; }

 

9.5.2 其他方法去改变string

1.

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string str1 = "helloworld!";

    const char *li = "ha ni shi";

    str1.assign(li);//"ha ni shi"
    str1.assign(5, 'p');//复制为5个'p'
    str1.append("aisheng");//字符串后加aisheng
    str1.replace(5, 2, "mu");//从str1[5]开始,移除两个字符,插入mu
     
    cout << str1 << endl;
    system("PAUSE");
    return 0;
}

oppend操作符是短的方法,在最后插入。

 

9.5.3 string搜索操作符

库定义npos为string::size_type类型,初始值为-1

 

字符串搜索函数的返回值为无符号类型(unsigned)

 

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string str = "helloworld";

    auto i = str.find("ld");
    //在str发现"ld"
    auto m = str.find_first_of("abcde");
    //在str发现第一个在"abcde"中的字符
    auto n = str.find_first_not_of("hello");
    //在str发现第一个不在"hello"中的字符
    auto j = str.find_last_of("abclh");
    //在str发现第一个在"abclh"中的字符

    if (i != str.npos) {
        cout << "string position is: " << i << endl;
    }

    if (m != str.npos) {
        cout << "string position is: " << m << endl;
    }

    if (n != str.npos) {
        cout << "string position is: " << n << endl;
    }

    if (j != str.npos) {
        cout << "string position is: " << j << endl;
    }

    system("PAUSE");
    return 0;
}
posted @ 2018-10-24 15:51  Hk_Mayfly  阅读(216)  评论(0)    收藏  举报