[UE 4]C++stringの使い方と例

45536 ワード

使用する場合:
stringはC++標準ライブラリの重要な部分であり、主に文字列処理に用いられる.入出力ストリーム方式で直接操作してもよいし、ファイルなどで操作してもよい.同時にC++のアルゴリズムライブラリはstringに対してもよくサポートされており、stringはc言語の文字列との間に良好なインタフェースを持っている.いくつかの弊害もあるが、欠点は隠さない. その中で使用されるコードの多くはcpp公式サイトから来ており、例が非常に完備しているためだ.
宣言と初期化方法:
stringを使用するには、まずヘッダファイルにを追加します. 宣言も簡単
宣言:
string s;//    string   
string ss[10];//    string     

初期化:
等号を用いた初期化をコピー初期化,等号を用いない初期化を直接初期化と呼ぶ.
#include 
using namespace std;       //  :       ,     std::string

int main()
{
    ios::sync_with_stdio(false);
    string s;//
    string s1("ssss");//s1    “ssss”   
    string s2(s1);//s2 s1   
    string s3=s2;//s3 s2   
    string s4(10,'c');// s4   
    string s5="hiya";//     
    string s6=string(10,'c');//     ,           ,   s6

    //string s(cp,n)
    char cs[]="12345";
    string s7(cs,3);//     cs  3    s  

    //string s(s2,pos2)
    string s8="asac";
    string s9(s8,2);// s2          ,    s2 size

    //string s(s2,pos2,len2)
    string s10="qweqweqweq";
    string s11(s10,3,4);//s4 s3   3  4      ,  s3.size     
    return 0;
}

文字列処理:
substr操作:
注意substrにはパラメータとしての反復器の動作はありません
#include 
using namespace std;
int main()
{
    ios::sync_with_stdio(false);
    string s="abcdefg";

    //s.substr(pos1,n)        pos1   n       
    string s2=s.substr(1,5);//abcde

    //s.substr(pos)//    pos     
    string s3=s.substr(4);//efg

    return 0;
}

入力した位置が文字の長さを超えると、out_が放出されます.of_rangeの異常
Insertアクション:
コードはcpp公式サイトから来て、自分の整理を経て 注意反復器によるパラメータと符号なし数のパラメータの違い
#include 
using namespace std;
int main()
{
    ios::sync_with_stdio(false);
    string str="to be question";
    string str2="the ";
    string str3="or not to be";
    string::iterator it;

    //s.insert(pos,str)// s pos    str
    str.insert(6,str2);                 // to be the question

    //s.insert(pos,str,a,n) s pos    str     a    n   
    str.insert(6,str3,3,4);             // to be not the question

    //s.insert(pos,cstr,n)// pos    cstr          n   
    str.insert(10,"that is cool",8);    // to be not that is the question

    //s.insert(pos,cstr) s pos    cstr
    str.insert(10,"to be ");            // to be not to be that is the question

    //s.insert(pos,n,ch) s.pos      n ch
    str.insert(15,1,':');               // to be not to be: that is the question

    //s.insert(s.it,ch) s it            ch,            
    it = str.insert(str.begin()+5,','); // to be, not to be: that is the question

    //s.insert(s.it,n,ch)// s it          n ch
    str.insert (str.end(),3,'.');       // to be, not to be: that is the question...

    //s.insert(it,str.ita,str.itb) it           [ita,itb)    
    str.insert (it+2,str3.begin(),str3.begin()+3); // to be, or not to be: that is the question...

    return 0;
}

eraseアクション:
削除操作の実行 削除操作は3種類あります
  • posとlenを指定します.posが開始位置であり、posおよび後のlen-1文字列が削除されます
  • 反復器、反復器が指す文字を削除
  • 反復器範囲、この範囲の文字列を削除し、範囲左閉右開
  • コードはcpp公式サイトから
    #include 
    #include <string>
    
    int main ()
    {
      std::string str ("This is an example sentence.");
      std::cout << str << '
    '; // "This is an example sentence." str.erase (10,8); // ^^^^^^^^ // 8 std::cout << str << '
    '; // "This is an sentence." str.erase (str.begin()+9);// ^ // std::cout << str << '
    '; // "This is a sentence." // ^^^^^ str.erase (str.begin()+5, str.end()-9); // std::cout << str << '
    '; // "This sentence." return 0; }

    appendおよびreplace操作:
    append関数は、文字列の末尾に文字と文字列を追加するために使用できます.stringは演算子をリロードするので、+=操作で実現することもできます repalceはその名の通り、置き換えの意味で、先に削除し、その後増加します. コードはcppの公式サイトから来て、自分の解釈を添付します
    #include 
    #include <string>
    
    int main ()
    {
        std::string str;
        std::string str2="Writing ";
        std::string str3="print 10 and then 5 more";
    
        //      str2    
        str.append(str2);                       // "Writing "
        //    str3 6      3    
        str.append(str3,6,3);                   // "10 "
        //         5   
        str.append("dots are cool",5);          // "dots "
        //    
        str.append("here: ");                   // "here: "
        //  10 '.'
        str.append(10u,'.');                    // ".........."
        //  str3         
        str.append(str3.begin()+8,str3.end());  // " and then 5 more"
        //        ,     5 'A',        65   asc   65
        str.append<int>(5,65);                // "....."
        //                
        str+="lalala";
        std::cout << str << '
    '; return 0; }

    replaceの使用方法、replaceは符号なし整数で位置を探すことをサポートし、反復器で位置を探すこともサポートします
    #include 
    #include <string>
    
    int main ()
    {
        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:
    
        // Using positions:                 0123456789*123456789*12345
        std::string str=base;           // "this is a test string."
        // 9        4    str2  
        str.replace(9,5,str2);          // "this is an example string." (1)
        // 19         5    str  7        5     
        str.replace(19,6,str3,7,6);     // "this is an example phrase." (2)
        // 8        9           
        str.replace(8,10,"just a");     // "this is just a phrase."     (3)
        // 8        5           7     
        str.replace(8,6,"a shorty",7);  // "this is a short phrase."    (4)
        // 22     0    3     
        str.replace(22,1,3,'!');        // "this is a short phrase!!!"  (5)
        //        
        // Using iterators:                                               0123456789*123456789*
        str.replace(str.begin(),str.end()-3,str3);                    // "sample phrase!!!"      (1)
        str.replace(str.begin(),str.begin()+6,"replace");             // "replace phrase!!!"     (3)
        str.replace(str.begin()+8,str.begin()+14,"is coolness",7);    // "replace is cool!!!"    (4)
        str.replace(str.begin()+12,str.end()-4,4,'o');                // "replace is cooool!!!"  (5)
        str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful."    (6)
        std::cout << str << '
    '; return 0; }

    以上のreplace操作はinsertとeraseの操作の組み合わせで置き換えることができますが、replace操作はより便利です.
    assignアクション: assign操作は、vectorなどのカラムコンテナに存在します.stringはassignを使用して柔軟に値を割り当てることができる基本的な操作関数です. コードはcpp公式サイトから
    #include 
    #include <string>
    
    int main ()
    {
        std::string str;
        std::string base="The quick brown fox jumps over a lazy dog.";
    
        // used in the same order as described above:
        //   base   str
        str.assign(base);
        std::cout << str << '
    '; // base 10 8 str str.assign(base,10,9); std::cout << str << '
    '; // "brown fox" // 0 6 str str.assign("pangrams are cool",7); std::cout << str << '
    '; // "pangram" // str.assign("c-string"); std::cout << str << '
    '; // "c-string" // str 10 '*' str.assign(10,'*'); std::cout << str << '
    '; // "**********" // 10 '-' str.assign<int>(10,0x2D); std::cout << str << '
    '; // "----------" // base str.assign(base.begin()+16,base.end()-12); std::cout << str << '
    '; // "fox jumps over" return 0; }

    stringの検索操作:
    stringクラスには、パフォーマンスに優れ、使いやすいメンバーメソッドがたくさん用意されています.汎用アルゴリズムにも実用的なテクニックがたくさんあります.
    findとrfind関数:
    find関数は主に、呼び出した文字列に文字列が現れたかどうかを検索し、大文字と小文字が敏感です. コードはcpp公式サイトから
    #include 
    using namespace std;
    
    int main()
    {
        ios::sync_with_stdio(false);
        std::string str ("There are two needles in this haystack with needles.");
        std::string str2 ("needle");
    
        // different member versions of find in the same order as above:
        // str          needle,          ,      
        std::size_t found = str.find(str2);
        if (found!=std::string::npos)
        std::cout << "first 'needle' found at: " << found << '
    '; // str , found+1 6 found=str.find("needles are small",found+1,6); if (found!=std::string::npos) std::cout << "second 'needle' found at: " << found << '
    '; // str found=str.find("haystack"); if (found!=std::string::npos) std::cout << "'haystack' also found at: " << found << '
    '; // found=str.find('.'); if (found!=std::string::npos) std::cout << "Period found at: " << found << '
    '; // , str2 // let's replace the first needle: str.replace(str.find(str2),str2.length(),"preposition"); std::cout << str << '
    '; return 0; }

    rfind関数は最後に現れた一致文字列を探して、返される位置は依然として前後数です.
    #include 
    using namespace std;
    
    int main()
    {
        ios::sync_with_stdio(false);
        std::string str ("The sixth sick sheik's sixth sheep's sick.");
        std::string key ("sixth");//                    ^
        //rfind              
        std::size_t found = str.rfind(key);
        if (found!=std::string::npos)
        {
            cout<//  23
            str.replace (found,key.length(),"seventh");//   sixth   seventh
        }
    
        std::cout << str << '
    '; return 0; }

    検索の効率は非常に高く、stlソースの剖析を見たことがありませんが、kmpで実現したような気がします.ほほほ、自分で1つ書くことができます.
    find_….of関数:
  • find_first_of(args) argsのいずれかの文字が最初に表示された場所
  • を検索します.
  • find_last_of(args) 最後に出現した場所
  • find_fist_not_of(args) 検索argsにない最初の文字
  • find_last_not_of argsに表示されない最後の文字
  • を検索
    #include 
    using namespace std;
    
    int main()
    {
        ios::sync_with_stdio(false);
        std::string str1 ("Please, replace the vowels in this sentence by asterisks.");
        std::size_t found1 = str1.find_first_of("aeiou");
        //         *  
        while (found1!=std::string::npos)
        {
            str1[found1]='*';
            found1=str1.find_first_of("aeiou",found1+1);
        }
        std::cout << str1 << '
    '; // str2 std::string str2 ("look for non-alphabetic characters..."); std::size_t found2 = str2.find_first_not_of("abcdefghijklmnopqrstuvwxyz "); if (found2!=std::string::npos) { std::cout << "The first non-alphabetic character is " << str2[found2]; std::cout << " at position " << found2 << '
    '; } return 0; }

    find_last_ofとfind_last_not_ofはfirstとほぼ同じで、例コードは書かない.
    比較と変換:
    c言語の文字列比較関数strcmp関数のように、文字列比較操作をサポートし、python、C#言語の関数のように、数字と文字列を変換することをサポートします.いくつかの特性はC++11の中でしかありません. コンパイラバグに注意: MinGWコンパイラでバージョンが3.8未満の場合、c++11はサポートされていますが、文字列や配列の変換はサポートされていません.MinGWのバージョンを更新するか、g++を直接使用します.
    compare関数:
    strcmp関数と同様に、2つの文字列が等しい場合、0を返し、呼び出しオブジェクトはパラメータより1を返し、-1を返します. compareでは部分比較もサポートされており、6つのパラメータが設定できます.
    #include 
    using namespace std;
    
    int main()
    {
        ios::sync_with_stdio(false);
        string s1="123",s2="123";
        cout<//0
    
        s1="123",s2="1234";
        cout<//-1
    
        s1="1234",s2="123";
        cout<//1
    
        std::string str1 ("green apple");
        std::string str2 ("red apple");
    
        if (str1.compare(str2) != 0)
        std::cout << str1 << " is not " << str2 << '
    '; //str1 6 4 if (str1.compare(6,5,"apple") == 0) std::cout << "still, " << str1 << " is an apple
    "; if (str2.compare(str2.size()-5,5,"apple") == 0) std::cout << "and " << str2 << " is also an apple
    "; //str1 6 4 str2 4 4 if (str1.compare(6,5,str2,4,5) == 0) std::cout << "therefore, both are apples
    "; return 0; }

    stringは演算子を再ロードしているので、>を直接使用できます.
    数値変換:
    ioの部分では数値と文字列が互いに変換された例があり,stringstream関数を用い,c++11で定義された既成の関数呼び出しがあり,非常に便利である.
    stringと数値変換
     
    to_string(val)
    valをstringに変換する
    stoi(s,p,b)
    文字列sをpからb進法のintに変換する
    stol(s,p,b)
    long
    stoul(s,p,b)
    unsigned long
    stoll(s,p,b)
    long long
    stoull(s,p,b)
    unsigned long long
    stof(s,p)
    float
    stod(s,p)
    double
    stold(s,p)
    long double
    //注意、次のコードはMinGwでエラーが発生します!c++11を使用してコンパイルしても、to_を認識できません.string!
    #include 
    using namespace std;
    
    int main()
    {
        ios::sync_with_stdio(false);
        string s1;
        s1=to_string(100);
        cout<endl;
        int a=stoi(s1,0,10)+1;
        cout<endl;
    return 0;
    }

     
     
    転載先:https://www.cnblogs.com/timy/p/8624694.html