1. 程式人生 > 其它 >【上交ACM—語法基礎】String型別--花式String操作

【上交ACM—語法基礎】String型別--花式String操作

程式碼例子:

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

int main() {
    string s1("LaoWang");
    string s2 = "Liu";
    
    // 如果感興趣,可以在下方實現左邊表格裡string型別的花式操作,加深印象
    //常用功能
    s1.assign(s2);
    cout << s1 << endl;
    s1.append(s2);
    cout << s1 << endl;
    cout << "s1 - s2 = " << s1.compare(s2) << endl;
    cout << "s1(1, 4): " << s1.substr(0, 3) << endl;
    
    //訪問元素
    cout << s1[0] << s1.at(1);
    s1.at(2) = 'a';
    cout << "第一個字元" << s1.front() << endl;
    cout << "最後一個字元" << s1.back() << endl;

    //string與char相互轉換
    char arr[8];
    string s = "LaoWang";
    //-------.copy(char_arr, len, pos)函式返回copy的len值
    int len = s.copy(arr, 7);
    arr[len] = '\0';
    cout << arr << " " << s << endl;
    //-------.c_str函式和data函式

    char arr1[8];
    string s6  = "LaoWang";
    strcpy(arr1, s6.c_str());

    //增刪改查換
    string s3 = "LaoWang";
    s3.insert(3, "123");

    string s4 = "LaoWang";
    s4.erase(3, 1);
    cout << s4 << endl;

    int x = s1.find('L', 3);
    int y = s1.rfind('L', 3);
    cout << x << " " << y << endl;
    return 0;

    s1.push_back('1');
    cout << s1 << endl;
    s1.pop_back();
    cout << s1 << endl;

    s1.replace(3, 2, "123");
    cout << s1;
}