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!




优质内容筛选与推荐>>
1、c/c++强制类型转换
2、Symbol在对象中的作用
3、Apache Rewrite 规则详解
4、记一次Sql Server (MSSQLSERVER) 服务无法启动处理经历
5、IE6下click事件须返回return false;不然大问题来了


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn