淺談c++string類用法

借鑑於:
https://blog.csdn.net/liitdar/article/details/80498634

1.string轉換爲char*

使用c_str()方法或data()方法,這兩個方法在c++11標準中用法相同

//string 轉換爲char*
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string strOutput = "Hello World";
    //cout 可以直接輸出string類的對象的內容
    cout << "[cout] strOutput is:"
        << strOutput << endl;
    //string 轉換爲char*
    const char *pszOutput = strOutput.c_str();
    //因爲string對象一旦初始化就不可變
    //所以要加const
    //c_str()方法和data()方法在c++11版本中一樣
    printf("[printf] strOutput is:%s\n"
           , pszOutput);
    //printf()函數不能直接打印string類的
    //對象的內容,可以通過將string轉換爲
    //char*類型,在使用printf()函數打印
    return 0;
}

2.計算string長度和比較string字符串

#include <iostream>
#include <string>

#define HELLOSTR "Hello, World!"

using namespace std;

int main()
{
    string strOutput = "Hello, World!";
    
    int nLen = strOutput.length();
    // 計算字符串長度的方法
    cout << "The length of strOutput is:" 
        << nLen << endl;
    if (strOutput.compare(HELLOSTR) == 0) {
        // 比較字符串的方法
        cout << "strOutput equal with macro HELLOSTR"
            << endl;
    }

    return 0;
}

3.char* char[]轉換爲string

#include <iostream>
#include <string>

using namespace std;

int main()
{
    const char *pszName = "liitdar";
    char pszCamp[] = "alliance";

    string strName;
    string strCamp;

    strName = pszName;
    strCamp = pszCamp;
    //將char* char[]轉換爲string類型時,直接
    //進行賦值操作,將char* char[]的變量賦值
    //給string對象即可.
    //這裏的賦值實際上是將字符串的首地址賦值
    //給string對象了
    cout << strName << endl;
    cout << strCamp << endl;
    return 0;
}

4.string類的find方法

//使用string類的find方法, 在字符串中檢索
//子字符串是否存在.
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string strOutput = "|0|1|2|";
    string strObj = "|1|";
    
    size_t nLoc = strOutput.find(strObj);
    // find方法的返回類型爲size_t,
    // 如果檢索到子串,返回子串在字符串
    // 中的位置,如果沒有檢索到,返回
    // string::npos
    if (nLoc != string::npos) {
        cout << nLoc << endl;
    }

    return 0;
}

5.string類的insert方法

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string strDemo = "I am";

    strDemo.insert(2, " good.");
    //使用string類的insert方法,向字符串
    //前面插入字符(串)
    cout << "strDemo is:" << strDemo << endl;

    return 0;
}

發佈了13 篇原創文章 · 獲贊 5 · 訪問量 746
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章