• The STL string Class


    The STL string class std::string helps you in the following ways:

    • Reduces the effort of creation and manipulating strings
    • Increases the stability of the application being programmed by internally managing memory allocation details
    • Supplies copy constructor and assignment operators that automatically ensure that member strings get correctly copied
    • Supplies useful utility functions that help in copying, truncating, finding, and erasing  to name a few
    • Provides operators that help in comparisons
    • Focuses efforts on your application's primary requirements rather than on string manipulation details
    Working with the STL string Class

    The most commonly used string functions are
    • Copying
    • Concatenating
    • Finding characters and substrings
    • Truncating
    • String reversal and case conversion are achieved using algorithms provided by the standard library
    Instantiating the STL string and Making Copies
    #include <string>
    #include
    <iostream>

    int main ()
    {
    using namespace std;
    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);
    cout
    << "str2Copy is: " << str2Copy << endl;

    // Initialize a string to the first 5 characters of another
    std::string strPartialCopy (pszConstString, 5);
    cout
    << "strPartialCopy is: " << strPartialCopy << endl;

    // Initialize a string object to contain 10 'a's
    std::string strRepeatChars (10, 'a');
    cout
    << "strRepeatChars is: " << strRepeatChars << endl;

    return 0;
    }

    Output:  

      Constant string is: Hello String!

      strFromConst is: Hello String!

      str2Copy is: Hello String!

      strPartialCopy is: Hello

      strRepeatChars is: aaaaaaaaaa

    Accessing a string and Its Contents

    #include <string>
    #include
    <iostream>

    int main ()
    {
    using namespace std;

    // The sample string
    string strSTLString ("Hello String");

    // Access the contents of the string using array syntax
    cout << "Displaying 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 contents of a string using iterators
    cout << "Displaying 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;

    return 0;
    }

    Output:

      Displaying the elements in the string using array-syntax:

      Character [0] is: H

      Character [1] is: e

      Character [2] is: l

      Character [3] is: l

      Character [4] is: o

      Character [5] is:

      Character [6] is: S

      Character [7] is: t

      Character [8] is: r

      Character [9] is: i

      Character [10] is: n

      Character [11] is: g

      Displaying the contents of the string using iterators:

      Character [0] is: H

      Character [1] is: e

      Character [2] is: l

      Character [3] is: l

      Character [4] is: o

      Character [5] is:

      Character [6] is: S

      Character [7] is: t

      Character [8] is: r

      Character [9] is: i

      Character [10] is: n

      Character [11] is: g

    String Concatenation

    #include <string>
    #include
    <iostream>

    int main ()
    {
    using namespace std;

    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;

    return 0;
    }

    Output:

      Hello String!

      Hello String! Fun is not needing to use pointers!

      Hello String! Fun is not needing to use pointers when working with strings. You

      however still can!

    Finding a Character or Substring in a string

    #include <string>
    #include
    <iostream>

    int main ()
    {
    using namespace std;

    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 instances 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 instances 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
    size_t nCharSearchOffset = nCharacterOffset + 1;

    nCharacterOffset
    = strSample.find(chCharToSearch,nCharSearchOffset);
    }

    return 0;
    }

    Output:

      The sample string is:

      Good day String! Today is beautiful!

      First instance of “day” was found at offset 5

      Locating all instances of substring “day”

      “day” found at offset 5

      “day” found at offset 19

      Locating all instances of character ‘a’

      ‘a’ found at position: 6

      ‘a’ found at position: 20

      ‘a’ found at position: 28

    Truncate a STL string

    #include <string>
    #include
    <algorithm>
    #include
    <iostream>

    int main ()
    {
    using namespace std;

    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);
    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;

    return 0;
    }

    Output:

      The original sample string is:

      Hello String! Wake up to a beautiful day!

      Truncating the second sentence:

      Hello String!

      Erasing character ‘S’ from the sample string:

      Hello tring!

      Erasing a range between begin() and end():

      The string is empty

    String Reversal

    // Listing 17.6 - Reversing an STL String
    #include <string>
    #include
    <iostream>
    #include
    <algorithm>

    int main ()
    {
    using namespace std;

    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;

    return 0;
    }

    Output:

      The original sample string is:

      Hello String! We will reverse you!

      After applying the std::reverse algorithm:

      !uoy esrever lliw eW !gnirtS olleH

    String Case Conversion

    // Listing 17.7 - Performing Case Conversions on an STL String Using std::transform
    #include <string>
    #include
    <iostream>
    #include
    <algorithm>

    int main ()
    {
    using namespace std;

    cout
    << "Please enter a string for case-convertion:" << 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;

    return 0;
    }

    Output:

      Please enter a string for case-conversion:

      > ConverT thIS StrINg!

      The string converted to upper case is:

      CONVERT THIS STRING!

      The string converted to lower case is:

      convert this string!




  • 相关阅读:
    实现带有头结点的链表
    数据结构之链式线性表
    HDU 1010 dfs+奇偶剪枝
    数据结构之顺序线性表
    POJ 1753 dfs+枚举
    HDU 4277 dfs+set去重
    平衡二叉树
    线性素数筛+欧拉线性筛(证明)
    dp--2019南昌网络赛B-Match Stick Game
    线段树+单调栈+前缀和--2019icpc南昌网络赛I
  • 原文地址:https://www.cnblogs.com/DanielZheng/p/2134343.html
Copyright © 2020-2023  润新知