C++学习3 | string类

#include <string>

 #include <string>

 using namespace std;

 相当于用string替换C语言中char*

int main()
{
    const char* p = "Hanoi_ahoj";   // 1
    cout << p << endl;
    char str[] = "Hanoi_ahoj";      // 2
    cout << str << endl;
    cout << "Hanoi_ahoj" << endl;   // 3
    
    string s1 = "Hanoi_ahoj";   // 1
    cout << s1 << endl;
    string s2("cool");          // 2
    cout << s2 << endl;
    
    // 拼接
    string s3 = s1 + " " + s2;  // 1
    cout << s3 << endl;
    s3 += "!";                  // 2
    cout << s3 << endl;
    s3.append(s2);              // 3
    cout << s3 << endl;
    // 交换
    s3.swap(s1);    // s3 <-> s1
    cout << s3 << endl;
    // 长度
    cout << s3.length() << endl;
    // 替换
    s3.replace(s3.find("_",0),1,".");   //在s3中找到_ 一个字符,替换成.
    cout << s3 << endl;
    s3.replace(s3.find("ahoj",0),4,"happy");
    cout << s3 << endl;
    
    // 比较
    if(s1 == s2)
        cout << "yes" << endl;
    else
        cout << "no" << endl;
    
    return 0;
}

输出: 

更多内容请阅读 basic_string类的内容。

猜你喜欢

转载自blog.csdn.net/Hanoi_ahoj/article/details/81415290