C++におけるSTLにおけるstringクラスの使用

35130 ワード

標準C++のstringクラスを使用するには、#include//注意はい、いいえ、帯を含む必要があります.hはC言語のヘッダファイルusing std::string;using  std::wstring; またはusing namespace std;
コンストラクション関数string()string( size_type length, char ch ); string( const char *str ); string( const char *str, size_type length ); string( string &str, size_type index, size_type length ); string( input_iterator start, input_iterator end );
文字列のコンストラクション関数は、•lengthを長いchのコピー(すなわちlength個ch)•strを初期値(任意の長さ)•indexをインデックスとして開始するサブ列、長さlength、またはstartからendまでの要素を初期値とする新しい文字列を作成する.例えばstring str 1(5,'c');    string str2( "Now is the time...");     string str3( str2, 11, 4 );     cout << str1 << endl;     cout << str2 << endl;     cout << str3 << endl;
==,>,=,<=,and!=比較文字列+または+=オペレータで2つの文字列を接続することができ、[]で特定の文字を取得することができる.テキスト(append)構文の追加:basic_string &append( const basic_string &str );   basic_string &append( const char *str );   basic_string &append( const basic_string &str, size_type index, size_type len );   basic_string &append( const char *str, size_type num );   basic_string &append( size_type num, char ch );   basic_string &append( input_iterator start, input_iterator end );
append()関数は、•文字列の末尾にstrを追加する、•文字列の末尾にstrのサブ列を追加する、サブ列はindexインデックスで始まり、長さはlen•文字列の末尾にstrのnum文字を追加する、•文字列の末尾にnum文字chを追加する、•文字列の末尾に反復器startとendで表す文字列を追加する.たとえば、string str="Hello World";    str.append( 10, '!' );     cout << str << endl; ハローワールドを表示!!!割り当て(assign)構文:basic_string &assign( const basic_string &str );   basic_string &assign( const char *str );   basic_string &assign( const char *str, size_type num );   basic_string &assign( const basic_string &str, size_type index, size_type len );   basic_string &assign( size_type num, char ch );
関数は、•strを文字列に、•strの先頭num文字を文字列に、•strのサブストリングを文字列に、サブストリングをindexインデックスに、長さlen•num文字chを文字列に、値を割り当てる.たとえば、string str 1、str 2="War and Peace";    str1.assign( str2, 4, 3 );       cout << str1 << endl; and at構文の表示:reference at(size_type index);
at()関数はindex位置の文字を指す参照を返す.indexが文字列の範囲内にない場合、at()は「out of range」エラーを報告し、out_を放出します.of_range異常.たとえば、string text="ABCDEF";    char ch = text.at( 2 ); 文字'C'を表示します.begin構文:iterator begin()
begin()関数は、文字列の最初の要素を指す反復器を返します.c_str構文:const char*c_str();
c_str()関数は、本文字列と同じ内容の正規C文字列を指すポインタを返す.容量(capacity)構文:size_type capacity();
Capacity()関数は、より多くの空間を再申請する前に文字列が収容できる文字数を返す.この数字は少なくともsize()と同じ大きさです.検索構文:size_type find( const basic_string &str, size_type index );   size_type find( const char *str, size_type index );   size_type find( const char *str, size_type index, size_type length );   size_type find( char ch, size_type index );
find()関数:•strが文字列に最初に現れる位置を返します(indexから検索します).見つからない場合はstring::npos、•strが文字列に最初に現れる位置を返します(indexから検索します.長さはlengthです).見つからない場合はstring::npos、•文字列に最初に現れる位置を返します.(indexから検索).見つからない場合はstring::npos、例えばstring str 1(「Alpha Beta Gamma Delta」);    unsigned int loc = str1.find( "Omega", 0 );     if( loc != string::npos )       cout << "Found Omega at "<< loc << endl;     else       cout << "Didn't find Omega"<< endl; 挿入(insert)構文:iterator insert(iterator i,const char&ch);  basic_string &insert( size_type index, const basic_string &str );   basic_string &insert( size_type index, const char *str );   basic_string &insert( size_type index1, const basic_string &str, size_type index2, size_type num );   basic_string &insert( size_type index, const char *str, size_type num );   basic_string &insert( size_type index, size_type num, char ch );   void insert( iterator i, size_type num, const char &ch );   void insert( iterator i, iterator start, iterator end );
Insert()関数の機能は非常に多い:•反復器iが表す位置の前に1文字chを挿入する•文字列の位置にindexが文字列strを挿入する•文字列の位置にindexが文字列strのサブストリングを挿入する(index 2から長いnum文字)•文字列の位置にindexが文字列strのnum文字を挿入する•文字列の位置indexにnum文字chのコピーを挿入する、•反復器iが示す位置の前にnum文字chのコピーを挿入する、•反復器iが示す位置の前に文字を挿入し、startからendで終了する.置換(replace)構文:basic_string &replace( size_type index, size_type num, const basic_string &str );   basic_string &replace( size_type index1, size_type num1, const basic_string &str, size_type index2,   size_type num2 );   basic_string &replace( size_type index, size_type num, const char *str );   basic_string &replace( size_type index, size_type num1, const char *str, size_type num2 );   basic_string &replace( size_type index, size_type num1, size_type num2, char ch );   basic_string &replace( iterator start, iterator end, const basic_string &str );   basic_string &replace( iterator start, iterator end, const char *str );   basic_string &replace( iterator start, iterator end, const char *str, size_type num );   basic_string &replace( iterator start, iterator end, size_type num, char ch );
replace()関数:•strのnum文字をこの文字列の文字に置き換え、indexから•strのnum 2文字(index 2から)で文字を置き換え、index 1から最大num 1文字•strのnum文字(indexから)で文字を置き換える•strのnum文字(indexから)で文字を置き換える•strのnum 2文字(index 2から)本文字列の文字を置換し、index 1からnum 1文字•num 2 ch文字で本文字列の文字を置換し、indexから•strの文字で本文字列の文字を置換し、反復器startとend指示範囲•strのnum文字で本文字列の内容を置換し、反復器startとendは例示を指すこの文字列の内容をnum個のch文字で置き換える、反復器startとendの指示範囲.たとえば、次のコードは文字列「They say he carved it himself...find your soul-mate,Homer.」を表示します.    string s = "They say he carved it himself...from a BIGGER spoon";     string s2 = "find your soul-mate, Homer.";
    s.replace( 32, s2.length(), s2 );
    cout << s << endl; size構文size_type size();
size()関数は、文字列に現在存在する文字数を返します.substr構文:basic_string substr( size_type index, size_type num = npos );
substr()は、indexからnum文字の長い文字の文字列を返します.指定されていない場合は、デフォルトstring::nposになります.これにより、substr()関数はindexから始まる残りの文字列を簡単に返します.例:string s(「What we have here is a failure to communicate」)
    string sub = s.substr(21);
    cout << "The original string is "<< s << endl;     cout << "The substring is "<< sub << endl; 表示:The original string is What we have here is a failure to communicate The substring is a failure to communicate交換(swap)構文:void swap(basic_string&str);
swap()関数はstrと本文字列を交換します.例:string first(「This comes first」);    string second( "And this is second");     first.swap( second );     cout << first << endl;     cout << second << endl; 表示:And this second This comes first data構文:const char*data()
data()関数は、自分の最初の文字を指すポインタを返す.
/*string関数デモ*/
/*****************************************
 * Copyright (C) 2018 * Ltd. All rights reserved.
 *
 * File name   : string.cpp
 * Author      : longbin
 * Created date: 2018-08-01 19:01:50
 * Description :
 *
 *******************************************/
#include 
#include 
#include 

#include 
#include 
using namespace std;

#define print(x) std::cout<<__func__>>"<<__line__>>"<
    //                   string  (InputIterator first, InputIterator last);

    string str0("hello c++ string");
    print(str0);
    // 1 empty string constructor (default constructor)
    // Constructs an empty string, with a length of zero characters.
    string str1;
    print(str1);
    // strcpy(str1, "hello c++ string str1."); // error
    // str1 = str0; // OK

    // 2 copy constructor
    // Constructs a copy of str.
    string str2(str0);
    print(str2);

    // 3 substring constructor
    string str3(str0, 3, 5); //   +  
    print(str3);

    // 4 from c-string
    // Copies the null-terminated character sequence (C-string) pointed by s.
    string str4("hello c++ string from c-string");
    print(str4);

    // 5 from buffer
    // Copies the first n characters from the array of characters pointed by s.
    string str5("hello c++ string from c-string buf", 20); //  
    print(str5);

    // 6 fill constructor
    // Fills the string with n consecutive copies of character c.
    string str6(6, 's');
    print(str6);

    // 7 range constructor
    // Copies the sequence of characters in the range [first,last), in the same order.
    string str7(str0.begin(), str0.begin()+5);
    print(str7);
    // string_construct>>30>>str0# hello c++ string
    // string_construct>>34>>str1#
    // string_construct>>41>>str2# hello c++ string
    // string_construct>>45>>str3# lo c+
    // string_construct>>50>>str4# hello c++ string from c-string
    // string_construct>>55>>str5# hello c++ string fro
    // string_construct>>60>>str6# ssssss
    // string_construct>>65>>str7# hello
}

void string_assign()
{
    //string (1)      string& operator= (const string& str);
    //c-string (2)    string& operator= (const char* s);
    //character (3)   string& operator= (char c);
    string s1, s2, s3;
    s1 = "string test"; // (2)
    s2 = 't';           // (3)
    s3 = s1 + s2;       // (1)
    string s = "hello"; // 1 empty string constructor 2. c-string assign;

    // string (1)     string& assign (const string& str);
    // substring (2)  string& assign (const string& str, size_t subpos, size_t sublen);
    // c-string (3)   string& assign (const char* s);
    // buffer (4)     string& assign (const char* s, size_t n);
    // fill (5)       string& assign (size_t n, char c);
    // range (6)  template 
    //                string& assign (InputIterator first, InputIterator last);

    string base = "c++ string assign test";
    string str;
    char str7[] = "hello str7.";

    str.assign(base);                   // (1)
    print(str);
    str.assign(base, 4, 6);             // (2)   +  
    print(str);
    str.assign("assign from c-string"); // (3)
    print(str);
    str.assign(str7);                   // (3)
    print(str);

    str.assign("assign from buffer", 20); // (4)   
    print(str); // assign from bufferh
    str.assign(8, '*');                   // (5)
    print(str);
    // str.assign(10, 0x2D);            // (5)
    print(str); // ----------
    str.assign(base.begin()+4, base.end()); // (6)
    print(str);
}

void string_clear()
{
    return;
    // Erases the contents of the string, which becomes an empty string (with a length of 0 characters).
    char c;
    std::string str;
    std::cout << "Please type some lines of text. Enter a dot (.) to finish:
"; do { c = std::cin.get(); str += c; if (c=='
') { std::cout << str; str.clear(); } } while (c!='.'); } void string_c_str() { // Get C string equivalent // Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. // This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end. string str1 = "hello c++ string c_str()"; print(str1); print(str1.c_str()); char buf[128] = {0}; // strcpy(buf, str1); // error strcpy(buf, str1.c_str()); // OK print(buf); char * cstr = new char[str1.length() + 1]; strcpy(cstr, str1.c_str()); // cstr now contains a c-string copy of str print(cstr); } void string_data() { // c_str() '\0' , data() , '\0' , ; // Returns a pointer to an array that contains the same sequence of characters as the characters that make up the value of the string object. // Accessing the value at data()+size() produces undefined behavior: There are no guarantees that a null character terminates the character sequence pointed by the value returned by this function. See string::c_str for a function that provides such guarantee. string str = "hello c++ string"; const char *p = "hello c++ string"; if (str.length() == strlen(p)) { cout << "str and p have the same length." << endl; if (memcmp(p, str.data(), str.length())) { cout << "str and p have the same content." << endl; } } } void string_at() { // Get character in string // Returns a reference to the character at position pos in the string. string str1 = "1234567890"; print(str1); //1234567890 print(str1.at(3)); //4 // print(str1.at(str1.length())); // out of range print(str1[3]); // print(str1[-1]); // } void string_begin_end() { string str1 = "1234567890"; string::iterator it; for (it = str1.begin(); it != str1.end(); it++) { print(*it); } print(*str1.begin()); //1 print(*str1.end()); // print(*(str1.end()-1)); //0 } void string_append() { // string (1) string& append (const string& str); // substring (2) string& append (const string& str, size_t subpos, size_t sublen); // c-string (3) string& append (const char* s); // buffer (4) string& append (const char* s, size_t n); // fill (5) string& append (size_t n, char c); // range (6) template // string& append (InputIterator first, InputIterator last); string str1 = "hello "; string str2 = "c++ "; print(str1); print(str2); str1.append(str2); // (1) cout << "str1.append(str2): " << str1 << endl; //hello c++ str1.append(str2, 1, 2); // (2) cout << "str1.append(str2, 1, 2): " << str1 << endl; //hello c++ ++ str1.append("good"); // (3) cout << "str1.append(\"good\"): " << str1 << endl; //hello c++ ++good str1.append("good", 3); // (4) cout << "str1.append(\"good\", 3): " << str1 << endl;//hello c++ ++goodgoo str1.append(5, '-'); // (5) cout << "str1.append(5, '-'): " << str1 << endl; //hello c++ ++goodgoo----- str1.append(str2.begin()+1, str2.end()-1); // (6) cout << "str1.append(str2.begin()+1, str2.end()-1): " << str1 << endl; //hello c++ ++goodgoo-----++ } void string_replace() { // string (1) string& replace (size_t pos, size_t len, const string& str); // string& replace (iterator i1, iterator i2, const string& str); // substring (2) string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen); // c-string (3) string& replace (size_t pos, size_t len, const char* s); // string& replace (iterator i1, iterator i2, const char* s); // buffer (4) string& replace (size_t pos, size_t len, const char* s, size_t n); // string& replace (iterator i1, iterator i2, const char* s, size_t n); // fill (5) string& replace (size_t pos, size_t len, size_t n, char c); // string& replace (iterator i1, iterator i2, size_t n, char c); // range (6) template // string& replace (iterator i1, iterator i2, InputIterator first, InputIterator last); // 0123456789*23456789*123 std::string base = "this is a test string."; std::string str2 = "n example"; std::string str3 = "sample phrase"; std::string str4 = "useful."; // replace signatures used in the same order as described above: // 2 , // Using positions: 0123456789*123456789*12345 std::string str = base; // "this is a test string." str.replace(9, 5, str2); // "this is an example string." (1) str[9:+5] length() print(str1.capacity()); print(str1.max_size()); str1 = "0123456789*123456789*123456789*123456789"; print(str1.length()); //40 print(str1.capacity()); //40 str1 = "hello c++"; print(str1.length()); //9 print(str1.capacity()); //40 CallInfo info; // c++ string , new malloc info.type = 5; info.status = 6; info.number = "123456789012"; print(sizeof(info)); //16 string str_hello = "hello world"; print(str_hello); print(sizeof(str_hello)); //8 string crash = "hello"; print(crash); crash.clear(); print(crash); // sizeof / / , / / ; // ,sizeof : // —— ; // —— ( , , 4); // —— ; // —— ; // —— 。 void; char arr0[20] = "hello arr0"; char arr1[] = "hello arr1"; char *pstr = new char[20]; strcpy(pstr, arr0); //sizeof ,sizeof ;sizeof , ; // sizeof() ; //sizeof(string) , sizeof(string) ; // ,string , ; string sstr = "hello sstr"; print(sizeof(arr0)); //20 print(sizeof(arr1)); //11 print(sizeof(pstr)); //8 print(sizeof(sstr)); //8 print(sstr); sizeof(sstr = "sizeof expr"); print(sstr); //"hello sstr" } void string_length() { // Return length of string // Returns the length of the string, in terms of bytes. // 0123456789*12345 string str("hello c++ string"); print(str.length()); //16 } void string_size() { // Return length of string // Returns the length of the string, in terms of bytes. // 0123456789*12345 string str("hello c++ string"); print(str.size()); //16 // length C ,string length; // STL , size, STL , STL , STL ; // string size()/length() , ; } void string_erase() { // sequence (1) string& erase (size_t pos = 0, size_t len = npos); // Erases the portion of the string value that begins at the character position pos and spans len characters; // or until the end of the string, if either the content is too short or if len is string::npos. // Notice that the default argument erases all characters in the string (like member function clear). // character (2) iterator erase (iterator p); // Erases the character pointed by p. // range (3) iterator erase (iterator first, iterator last); // Erases the sequence of characters in the range [first,last). // 0123456789*123456789*123 string str("hello c++ string example"); print(str); str.erase(17, 7); // (1) print(str); //hello c++ string str.erase(str.begin()+10); // (2) Erases the character pointed by p. print(str); //hello c++ tring str.erase(str.begin()+6, str.begin()+8); // (3) print(str); //hello + tring str.erase(); // (1) <==> str.clear(); print(str); // } void string_insert() { // string (1) string& insert (size_t pos, const string& str); // substring (2) string& insert (size_t pos, const string& str, size_t subpos, size_t sublen); // c-string (3) string& insert (size_t pos, const char* s); // buffer (4) string& insert (size_t pos, const char* s, size_t n); // fill (5) string& insert (size_t pos, size_t n, char c); // void insert (iterator p, size_t n, char c); // single character (6) iterator insert (iterator p, char c); // range (7) template // void insert (iterator p, InputIterator first, InputIterator last); // 0123456789*123 std::string str = "to be question"; std::string str2 = "the "; std::string str3 = "or not to be"; std::string::iterator it; // used in the same order as described above: // 0123456789*123456789*123456789 str.insert(6, str2); // (1) // to be the question print(str); str.insert(6, str3, 3, 4); // (2) // to be not the question str.insert(10, "that is cool", 8); // (4) // to be not that is the question str.insert(10, "to be "); // (3) // to be not to be that is the question str.insert(15, 1, ':'); // (5) // to be not to be: that is the question it = str.insert(str.begin()+5, ','); // (6) // to be, not to be: that is the question str.insert(str.end(), 3, '.'); // (5) // to be, not to be: that is the question... str.insert(it+2, str3.begin(), str3.begin()+3); // (7) // to be, or not to be: that is the question... print(str); } void string_empty() { // Test if string is empty // Returns whether the string is empty (i.e. whether its length is 0). string str0 = "hello c++ string"; string str1 = str0; string str2 = ""; string str3; print(str0.empty()); // 0 print(str1.empty()); // 0 print(str2.empty()); // 1 print(str3.empty()); // 1 str0.erase(); print(str0.empty()); // 1 str1.clear(); print(str1.empty()); // 1 } void string_compare() { // Compare strings //Compares the value of the string object (or a substring) to the sequence of characters specified by its arguments. // string (1) int compare (const string& str) const; // substrings (2) int compare (size_t pos, size_t len, const string& str) const; // int compare (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) const; // c-string (3) int compare (const char* s) const; // int compare (size_t pos, size_t len, const char* s) const; // buffer (4) int compare (size_t pos, size_t len, const char* s, size_t n) const; string str0 = "hello c++ string 0"; string str1 = "hello c++ string 1"; string str2 = "hello c++ string 2"; string str3 = "hello c++ string 0"; string str4 = "c++"; print(str1.compare(str2)); // (1) // <0 print(str0.compare(str3)); // (1) // ==0 print(str2.compare(str1)); // (1) // >0 print(str0.compare(6, 3, str4)); // (2) // ==0 print(str0.compare(6, 3, str1, 6, 3)); // (2) // ==0 print(str0.compare("hello c++ string 0")); // (3) // ==0 print(str0.compare(6, 3, "c++")); // (3) // ==0 print(str0.compare(6, 3, "c++ good", 3)); // (4) // ==0 } void string_copy() { // size_t copy (char* s, size_t len, size_t pos = 0) const; // Copy sequence of characters from string // The function does not append a null character at the end of the copied content. char buf[128] = "9876543210"; string str1 = "0123456789"; print(str1); size_t size = str1.copy(buf, 4, 3); //str len index print(buf); // 3456543210 print(strlen(buf)); // 10 print(size); // 4 buf[size] = '\0'; print(buf); // 3456 print(strlen(buf)); // 4 // std::copy() // template // OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result); // Copy range of elements // Copies the elements in the range [first,last) into the range beginning at result.] string str = "9876543210"; std::copy(str1.begin()+3, str1.begin()+7, str.begin()); // [3, 7); // no '\0' end; print(str); // 3456543210 print(strlen(str.data())); // 10 print(str.length()); // 10 str.assign(str1, 3, 4); print(str); // 3456 print(strlen(str.data())); // 4 print(str.length()); // 4 } void string_find() { // Find content in string // Searches the string for the first occurrence of the sequence specified by its arguments. // Return Vaulue: // The position of the first character of the first match. // If no matches were found, the function returns string::npos. // string (1) size_t find (const string& str, size_t pos = 0) const; // c-string (2) size_t find (const char* s, size_t pos = 0) const; // buffer (3) size_t find (const char* s, size_t pos, size_t n) const; // character (4) size_t find (char c, size_t pos = 0) const; string str = "hello c++ string find c++"; string f1 = "c++"; size_t fpos = 0; fpos = str.find(f1); // (1) cout << "first c++ found at: " << fpos << endl; fpos = str.find(f1, fpos+1); // (1) cout << "second c++ found at: " << fpos << endl; fpos = str.find("c++"); // (2) cout << "c++ found at: " << fpos << endl; fpos = str.find("c++", 2); // (2) cout << "c++ found at: " << fpos << endl; fpos = str.find("c++ good", 7, 3); // (3) //str[pos:] "c++ good"[:3] cout << "c++ found at: " << fpos << endl;// 22 // found "c++" from "hello c(++ string find c++)" fpos = str.find('+', 15); // (4) cout << "+ found at: " << fpos << endl; // 23 // found '+' from "hello c++ strin(g find c++)" } void string_substr() { // string substr (size_t pos = 0, size_t len = npos) const; // Generate substring // Returns a newly constructed string object with its value initialized to a copy of a substring of this object. string str1 = "hello c++ string substr."; string sub; size_t pos; pos = str1.find("c++", 0); sub = str1.substr(pos); print(sub); sub = str1.substr(pos, 3); print(sub); string info(17, '6'); size_t step = 6; // string info(20, '6'); // size_t step = 20; for (pos = 0; pos < info.length(); pos+=step) { cout << pos << ": " << info.substr(pos, step) << endl; } } std::vector<:string> split(std::string &line, const std::string & delim) { size_t pstart = 0; size_t phit = 0; std::string sstr; size_t length = line.length(); std::vector<:string> vstr; vstr.clear(); for (;pstart <= length;) { phit = line.find(delim, pstart); if (std::string::npos != phit) { /* find delim, get substr */ sstr = line.substr(pstart, phit-pstart); vstr.push_back(sstr); pstart = phit + delim.size(); } else { /* not find delim, append remaining str and break */ vstr.push_back(line.substr(pstart)); break; } } return vstr; } size_t split(const std::string &line, const std::string &delim, std::vector<:string> &vstr) { size_t pstart = 0; size_t phit = 0; std::string sstr; size_t length = line.length(); vstr.clear(); for (;pstart <= length;) { phit = line.find(delim, pstart); if (std::string::npos != phit) { /* find delim, get substr */ sstr = line.substr(pstart, phit-pstart); vstr.push_back(sstr); pstart = phit + delim.size(); } else { /* not find delim, append remaining str and break */ vstr.push_back(line.substr(pstart)); break; } } return vstr.size(); } template std::string join(T& val, std::string delim) { std::string str; typename T::iterator it; const typename T::iterator itlast = val.end()-1; for (it = val.begin(); it != val.end(); it++) { str += *it; if (it != itlast) { str += delim; } } return str; } std::string lstrip(const std::string &str, const std::string &delim="") { std::string rawstr = str; std::string::iterator it; std::string sp = delim; const size_t spl = sp.length(); if (0 == spl) { sp = " \t
\v\f\r"; // remove from head when startswith any of sp while (std::string::npos != sp.find(rawstr.at(0))) { rawstr.erase(0, 1); } } else { // remove from head when startswith sp while ((rawstr.length() >= spl) && (0 == rawstr.compare(0, spl, sp))) { print(rawstr); rawstr.erase(0, spl); } } return rawstr; } std::string rstrip(const std::string &str, const std::string &delim="") { std::string rawstr = str; std::string::iterator it; std::string sp = delim; const size_t spl = sp.length(); if (0 == spl) { sp = " \t
\v\f\r"; // remove from tail when endswith any of sp while (std::string::npos != sp.find(rawstr.at(rawstr.length()-1))) { rawstr.erase(rawstr.length()-1, 1); } } else { // remove from tail when endswith sp while ((rawstr.length() >= spl) && (0 == rawstr.compare((rawstr.length()-spl), spl, sp))) { rawstr.erase(rawstr.length()-spl, spl); } } return rawstr; } std::string strip(const std::string &str, const std::string &delim="") { std::string rawstr = str; std::string::iterator it; std::string sp = delim; const size_t spl = sp.length(); if (0 == spl) { sp = " \t
\v\f\r"; // remove from head when startswith any of sp while (std::string::npos != sp.find(rawstr.at(0))) { rawstr.erase(0, 1); } // remove from tail when endswith any of sp while (std::string::npos != sp.find(rawstr.at(rawstr.length()-1))) { rawstr.erase(rawstr.length()-1, 1); } } else { // remove from head when startswith sp while ((rawstr.length() >= spl) && (0 == rawstr.compare(0, spl, sp))) { rawstr.erase(0, spl); } // remove from tail when endswith sp while ((rawstr.length() >= spl) && (0 == rawstr.compare((rawstr.length()-spl), spl, sp))) { rawstr.erase(rawstr.length()-spl, spl); } } return rawstr; } bool startsWith(const std::string &src, const std::string &str) { int srcpos = 0; int srclen = src.length(); int sublen = str.length(); if (srclen < sublen) { return false; } return (0 == src.compare(srcpos, sublen, str)); } bool endsWith(const std::string &src, const std::string &str) { int srcpos = 0; int srclen = src.length(); int sublen = str.length(); if (srclen < sublen) { return false; } srcpos = srclen - sublen; return (0 == src.compare(srcpos, sublen, str)); } string mask(const string &src, int begin, int masklen) { string ret = src; string mask = ""; int length = (int)ret.length(); int replen = 0; int pos = begin; if (begin < 0) { // mask from tail pos = length + begin; } if ((pos < 0) || (pos >= length)) { // pos is out of range return ret; } if (masklen >= 0) { // std::min(masklen, (length-pos)) replen = ((length - pos) > masklen) ? masklen : (length - pos); } else { // mask from tail // std::min((-masklen), (pos+1)); replen = ((pos + 1) > -masklen) ? -masklen : (pos + 1); pos = (pos + 1) - replen; } if ((pos >= 0) && (pos < length)) { // cout << "true" << endl; mask.assign(replen, '*'); ret = ret.replace(pos, replen, mask); } return ret; } int main() { string split_line(30, '#'); cout << split_line << endl; string_construct(); string_assign(); string_clear(); string_c_str(); string_data(); string_at(); string_begin_end(); string_append(); string_erase(); string_insert(); string_replace(); string_capacity(); string_length(); string_size(); string_empty(); string_compare(); string_copy(); string_find(); string_substr(); // extended function // join(str, delim); vector vec(4, "good"); print(join(vec, "/")); string jstr(6, '0'); print(join(jstr, "-")); // split(str, delim); string str = "/usr/local/bin/python"; vector vt; (void)split(str, "/", vt); vector::iterator it; for (it = vt.begin(); it != vt.end(); it++) { print(*it); } // strip(str, chars); str = " 0hello good 0 "; str = strip(str, "0 "); print(str); print(str.length()); // strip(str); str = "
\r\t 0hello good 0 "; print(str); std::string lstr = lstrip(str); print(lstr); print(lstr.length()); std::string rstr = rstrip(str); print(rstr); print(rstr.length()); // mask string test = "01234567890"; print(test); print(mask(test, 1, 3)); //0***4567890 print(mask(test, 0, 4)); //****4567890 print(mask(test, -1, -3)); //01234567*** // startsWith print(startsWith(test, "01234")); //1 // endsWith print(endsWith(test, "7890")); //1 cout << split_line << endl; return 0; }

 
参考資料
https://blog.csdn.net/tengfei461807914/article/details/52203202 https://www.cnblogs.com/aminxu/p/4686320.html
http://www.cplusplus.com/reference/string/