STL::string類

本文摘自《21天學通C++》
最常用的字符串函數包括:

  • 複製
  • 連接
  • 查找字符和字符串
  • 截斷
  • 使用標準模版庫提供的算法實現字符串反轉和大小寫轉換
    使用STL string類,需包含頭文件
    1、實例化STL string及複製
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

int main()
{
    // 初始化一個常量字符串並將其賦值給一個STL string對象
    const char* pszConstString = "Hello String!";
    cout << "Constant string is:" << pszConstString << endl;

    std::string strFromConst(pszConstString);
    cout << "strFromConst is:" << strFromConst << endl;

    std::string str2("Hello String!");
    std::string str2Copy(str2);//用一個string對象來初始化另一個
    cout << "str2Copy is:" << str2Copy << endl;

    //Initialize a string to the first 5 characters of another
    std::string strPartialCopy(pszConstString, 5);
    //讓string的構造函數只接受輸入字符串的前n個字符
    cout << "strPartialCopy is:" << strPartialCopy << endl;

    //Initialize a string object to contain 10 'a's
    //初始化string對象,使其包含指定數量的特定字符
    std::string strRepeatChars(10, 'a');
    cout << "strRepeatChars is:" << strRepeatChars << endl;

    return 0;
}

2、訪問string及其內容
訪問STL string的字符內容,可使用迭代器,也可採用類似於數組的語法並使用下標運算符(【】)提供偏移量;要獲得string對象的C風格表示,可使用成員函數c_str(),

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

int main()
{
    string strSTLString("Hello String");

    cout << "Diaplaying characters using array-syntax:" << endl;
    for (size_t nCharCounter = 0; nCharCounter < strSTLString.length(); ++nCharCounter)
    {
        cout << "Character[" << nCharCounter << "] is:";
        cout << strSTLString[nCharCounter] << endl;
    }
    cout << endl;
    //Access the contants of a string using iterators
    cout << "Diapalying characters using iterators:" << endl;
    int nCharOffset = 0;
    string::const_iterator iCharacterLocator;
    for (iCharacterLocator = strSTLString.begin(); iCharacterLocator != strSTLString.end(); ++iCharacterLocator)
    {
        cout << "Character[" << nCharOffset++ << "] is:";
        cout << *iCharacterLocator << endl;
    }
    cout << endl;

    //Access the contents of a string as a C-style string
    cout << "The char* representation of the string is:";
    cout << strSTLString.c_str() << endl;

    getchar();
    return 0;
}

3、字符串連接
要連接字符串,可以使用運算符+=,也可使用成員函數append

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

int main()
{
    string strSample1("Hello");
    string strSample2("String!");

    //Concatenate
    strSample1 += strSample2;
    cout << strSample1 << endl << endl;

    string strSample3("Fun is not needing to use pointers!");
    strSample1.append(strSample3);
    cout << strSample1 << endl << endl;

    const char* pszConstString = "You however still can!";
    strSample1.append(pszConstString);
    cout << strSample1 << endl;

    getchar();
    return 0;
}

4、在string中查找字符或字符串
STL string類提供了成員函數find,該函數有多個重載版本,可在指定string對象中查找字符或字符串,

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

int main()
{
    string strSample("Good day String! Today is beautiful!");
    cout << "The sample string is:" << endl;
    cout << strSample << endl << endl;

    //Find substring "day" in it
    size_t nOffset = strSample.find("day", 0);

    //Check if the substring was found
    if (nOffset != string::npos)
        cout << "First instance of\"day\" was found at offset" << nOffset;
    else
        cout << "Substring not found." << endl;
    cout << endl << endl;

    cout << "Locating all instance of substring \"day\"" << endl;
    size_t nSubstringOffset = strSample.find("day", 0);
    while (nSubstringOffset != string::npos)
    {
        cout << "\"day\"found at offset" << nSubstringOffset << endl;

        //Make the 'find' function search the next character onwards
        size_t nSearchOffset = nSubstringOffset + 1;
        nSubstringOffset = strSample.find("day", nSearchOffset);
    }
    cout << endl;

    cout << "Locating all instance of character 'a'" << endl;
    const char chCharToSearch = 'a';
    size_t nCharacterOffset = strSample.find(chCharToSearch, 0);

    while (nCharacterOffset != string::npos)
    {
        cout << "'" << chCharToSearch << "' found";
        cout << " at position: " << nCharacterOffset << endl;
        //Make the 'find' function search forward from the next character onwards
        size_t nCharSearchOffset = nCharacterOffset + 1;
        nCharacterOffset = strSample.find(chCharToSearch, nCharSearchOffset);
    }

    getchar();
    return 0;
}

5、截短STL string
STL string類提供了erase函數,可用於:

  • 在給定偏移量和字符數時刪除指定數目的字符;
  • 在給定指向字符的迭代器時刪除字符;
  • 在給定由兩個迭代器指定的範圍時刪除該範圍內的字符。
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
#include <algorithm>
int main()
{
    string strSample("Hello String! Wake up to a beautiful day!");
    cout << "The original sample string is: " << endl;
    cout << strSample << endl << endl;

    //Delete characters from the string given position and count
    cout << "Truncating the second sentence: " << endl;
    strSample.erase(13, 28);//從第13個字符後刪除28個字符
    cout << strSample << endl << endl;

    //Find a character 'S' in the string using STL find algorithm
    string::iterator iCharS = find(strSample.begin(), strSample.end(), 'S');

    //If character found ,'erase' to deletes a character
    cout << "Erasing character 'S' from the sample string:" << endl;
    if (iCharS != strSample.end())
        strSample.erase(iCharS);
    cout << strSample << endl << endl;

    //Erase a range of characters using an overloaded version of erase()
    cout << "Erasing a range between begin() and end():" << endl;
    strSample.erase(strSample.begin(), strSample.end());

    //Verify the length after the erase() operation above
    if (strSample.length() == 0)
        cout << "The string is empty" << endl;
    getchar();
    return 0;
}

6、字符串反轉
需要包含頭文件
#include <algorithm>
判讀輸入的字符串是否是迴文:
std::string

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
#include <algorithm>
int main()
{
    string strSample("Hello String! We will reverse you!");
    cout << "The original sample string is: " << endl;
    cout << strSample << endl << endl;

    reverse(strSample.begin(), strSample.end());

    cout << "After applying the std::reverse algorithm: " << endl;
    cout << strSample;
    getchar();
    return 0;
}

7、字符串的大小寫轉換
std::transform,

#include "stdafx.h"
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    cout << "Please enter a string for case-conversion:" << endl;
    cout << "> ";

    string strInput;
    getline(cin, strInput);
    cout << endl;

    transform(strInput.begin(), strInput.end(), strInput.begin(), toupper);
    cout << "The string converted to upper case is: " << endl;
    cout << strInput << endl << endl;

    transform(strInput.begin(), strInput.end(), strInput.begin(), tolower);
    cout << "The string converted to lower case is: " << endl;
    cout << strInput << endl << endl;
    getchar();
    return 0;

7、基於模版STL string實現

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章