天天看點

【C++學習紀錄】string容器——字元串的拼接

string字元串的拼接

1、string &operator+=(const char *str) 重載+=操作符

2、string &operator+=(const char c) 重載+=操作符

3、string &operator+=(const string &str) 重載+=操作符

4、string &append(const char *s) 把字元串s連接配接到目前字元串末尾

5、string &append(const char *s, int n) 把字元串s前n個字元連接配接到目前字元串末尾

6、string &append(const string &s) 同operator+=(const string &str)

7、string &append(const string &s, int pos, int n) 字元串s中從pos位置開始的n個字元連接配接到目前字元串的末尾

一、string &operator+=(const char *str) 重載+=操作符

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str("hello ");
    const char *s = "world";
    str += s;
    cout << str << endl;
    system("pause");
}
           

運作結果:

hello world
請按任意鍵繼續. . .
           

二、string &operator+=(const char c) 重載+=操作符

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str("hello");
    char c = '!';
    str += c;
    cout << str << endl;
    system("pause");
}
           

運作結果:

hello!
請按任意鍵繼續. . .
           

三、string &operator+=(const string &str) 重載+=操作符

四、string &append(const char *s) 把字元串s連接配接到目前字元串末尾

五、string &append(const char *s, int n) 把字元串s前n個字元連接配接到目前字元串末尾

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str("My name is ");
    //在這個函數裡,後面接上的字元串隻能來自char*類型字元串,
    //不可以來自string
    char *temp = "Joe is my name.";
    str.append(temp, 3);
    cout << str << endl;
    system("pause");
}
           

運作結果:

My name is Joe
請按任意鍵繼續. . .
           

六、string &append(const string &s) 同operator+=(const string &str)

七、string &append(const string &s, int pos, int n) 字元串s中從pos位置開始的n個字元連接配接到目前字元串的末尾

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str("My name is ");
    string temp("Joe!");
    //注意,string類中首元素下标也為0
    //該函數中第三個參數應該是希望截取的字元串末尾下标+1,不是末尾下标本身
    //就是說這個函數會截取第三個參數之前到第二個參數之間的字元串
    //不包含第三個參數所指向下标的字元
    str.append(temp, 0, 4);//為了接上最後的感歎号字元,第三個參數是4而不是3
    cout << str << endl;
    system("pause");
}
           

運作結果:

My name is Joe!
請按任意鍵繼續. . .