Search

17.7 — std::string inserting

Inserting

Inserting characters into an existing string can be done via the insert() function.

string& string::insert (size_type index, const string& str)
string& string::insert (size_type index, const char* str)

  • Both functions insert the characters of str into the string at index
  • Both function return *this so they can be “chained”.
  • Both functions throw out_of_range if index is invalid
  • Both functions throw a length_error exception if the result exceeds the maximum number of characters.
  • In the C-style string version, str must not be NULL.

Sample code:

Output:

aaaa
aabbbbaa
aabbccccbbaa

Here’s a crazy version of insert() that allows you to insert a substring into a string at an arbitrary index:

string& string::insert (size_type index, const string& str, size_type startindex, size_type num)

  • This function inserts num characters str, starting from startindex, into the string at index.
  • Returns *this so it can be “chained”.
  • Throws an out_of_range if index or startindex is out of bounds
  • Throws a length_error exception if the result exceeds the maximum number of characters.

Sample code:

Output:

aa3456aa

There is a flavor of insert() that inserts the first portion of a C-style string:

string& string::insert(size_type index, const char* str, size_type len)

  • Inserts len characters of str into the string at index
  • Returns *this so it can be “chained”.
  • Throws an out_of_range exception if the index is invalid
  • Throws a length_error exception if the result exceeds the maximum number of characters.
  • Ignores special characters (such as ”)

Sample code:

Output:

aabcdaa

There’s also a flavor of insert() that inserts the same character multiple times:

string& string::insert(size_type index, size_type num, char c)

  • Inserts num instances of char c into the string at index
  • Returns *this so it can be “chained”.
  • Throws an out_of_range exception if the index is invalid
  • Throws a length_error exception if the result exceeds the maximum number of characters.

Sample code:

Output:

aaccccaa

And finally, the insert() function also has three different versions that use iterators:

void insert(iterator it, size_type num, char c)
iterator string::insert(iterator it, char c)
void string::insert(iterator it, InputIterator begin, InputIterator end)

  • The first function inserts num instances of the character c before the iterator it.
  • The second inserts a single character c before the iterator it, and returns an iterator to the position of the character inserted.
  • The third inserts all characters between [begin,end) before the iterator it.
  • All functions throw a length_error exception if the result exceeds the maximum number of characters.

18.1 -- Input and output (I/O) streams
Index
17.6 -- std::string appending

20 comments to 17.7 — std::string inserting

  • Brian

    Glad to see you back! These tuts are much appreciated by many people!

  • Sean

    “I’m baaaaaaaaack.”

  • abcd

    Hi Alex,

    I am glad that you are getting some time to write these tutorials.
    These are the best I have seen so far, and perhaps better than some of the course books and textbooks. Please continue this excellent work and I hope people can help and contribute as much as they can for all your hard work.
    I am eagerly waiting for tutorials on STL, e.g vectors, allocators, and other advanced topics. Your tutorials are very simple to understand and comprehend. The examples you give are great.

    Thanks again for all your work. I am sure, all the newbies like us will be always thankful to you for teaching us C++. Thanks a lot. May God bless you!

  • Skippeh

    The HTML symbol codes seems to be “broken” in the code examples.

  • octavsly

    HTML codes broken. Example of what I see.

    string sString("aaaa");
    cout << sString << endl;

  • octavsly

    🙂 got replaced correctly

  • X

    I love your tutorials Man. They are so beautiful. Best tutorials i could find on web. Thank you very much 🙂

  • Jackson maduranga_SAC

    PLEASE HELP ME TO SOLVE THIS !!!
    I wrote this code recently and found that it is having a error.
    some times it prints the first position as 0
    if anyone can help me i will appriciate , thank you !
    THE CODE IS AS FOLLOWS
    #include
    using namespace std;
    int NP,NS;

    struct students
    {
    int number;
    int marks[15];
    long int total;
    float mean;
    int pos ;
    }a[50 ];
    // innnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
    void getinput()
    {
    int j,k;
    cout << " 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 \n"<<endl;
    for(j=1;j<=NP;j++)
    {cout << "No:("<<j<<")";a[j-1].number=j;
    for(k=1;k> a[j-1].marks[k-1];cout << " ";}
    cout << endl;
    }
    }
    // totalllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
    void total_mean()
    {
    int i;
    for(i=1;i<=NP;i++)
    {
    int j;
    int k= 0;
    for(j=1;j<=NS;j++)
    {
    k=k+a[i-1].marks[j-1];
    }
    a[i-1].total = k;
    a[i-1].mean =(float)k/NS;
    }
    }
    //shoooooooow
    void showoutput()
    {
    int i,j;
    cout << " \tTOTAL\tMEAN\t\tPOSITION\n"<< endl;
    for(i=1;i<=NP;i++)
    {
    cout << "No("<<i<<")\t" << a[i-1].total << "\t" << a[i-1].mean<<"\t\t"<< a[i-1].pos<<endl;
    cout << "-------------------------------------------------"<<endl;
    }
    }
    //posssssssssssssssssssssssssssssssssssssssssssssssssss
    void pos()
    {
    int i,j,k;
    long int arr[50];
    for(i=1;i<=NP;i++)
    {
    arr[i-1]=a[i-1].total;
    }
    for(j=1;j=j;k-)
    {if(arr[k]>arr[k-1])
    {
    int temp = arr[k];
    arr[k] = arr[k-1];
    arr[k-1] = temp;}
    }
    }
    // dec pos
    int m,n;
    for(m=1;m<=NP;m++)
    {
    for(n=1;n<=NP;n++)
    {
    if(arr[m-1]==a[n-1].total)
    a[n-1].pos = m;
    }
    }

    //cheaking purposes
    cout << "****#” << endl;
    int c;
    for(c=1;c<=NP;c++)
    {cout << arr

    << endl;}
    cout << "************" << endl;
    cout << "_______________________________________________________________________________"<<endl;

    // END cheak

    }

    //chhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
    void CHEAK()
    {
    int i;
    for(i=1;i<=NP;i++)
    {
    cout << "St No:"<<i << ":\t";
    {int j; for(j=1;j<=NS;j++){cout << a[i-1].marks[j-1] << " " ;}
    cout << endl;
    }
    }
    }

    int main()
    {

    cout << "\n \t ***** (marks_sheet) by - Maduranga S Jayasooriya - *****\n_____________________________________________________________________________" << endl;
    cout <>NP;
    cout <>NS;
    cout << "\n-------------------------------------(enter the marks)"<< endl;
    getinput();
    total_mean();
    pos();
    cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" << endl;
    showoutput();
    cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"<<endl;
    cout << "_______________________________________________________________________________" <<endl;
    cout << " -[maduranga]-"<<endl;

    system("pause");
    return 0;
    }

  • Thibaut

    I’m just writing this comment to thank you for these tutorials. Helping me a lot. Keep up the good work.

  • Peng

    So i have finished this tutorial, where i can go next step?
    i think that’s most people will wonder.
    Thank you for all of your effort for this tutorial 🙂
    Very nice, keep it! 🙂 🙂

    • Alex

      Anywhere you want! 🙂

      Some possible next steps:
      * Learn more about data structures and algorithms.
      * Learn more about the functionality of the standard template library.
      * Learn more about 3d graphics (openGL).
      * Learn more about graphical user interfaces (e.g. WxWidgets, QT).
      * Learn more about graphical application development (e.g. SDL).

      • Mekacher Anis

        thaaaaaaaaaaaaaaaaannnnnnnnnnnnnkkkkkkkkk’s , but is it alright that I still don’t understand somethings ?

        • Alex

          Of course. You can always come back to a subject later, when it becomes relevant. By then, hopefully you’ll have more experience or context in which to understand what eluded you before.

  • Amit Saroj

    Hi Alex, Enjoyed your teachings, I want to expand more, can you give any reference book or site to study Data Structures like Linked list, Tree, Stack and Queues.
    I tried to study them across various resources, but it makes more confusing.

    • Alex

      I don’t have any good recommendations in this area. Most of the reference material I’ve run across is borderline inscrutable. 🙁

  • PV

    Hi Alex,
    Could you please insert an example with using iterators? I looked back at the section on iterators, with which I did not have problems, but here I am confused.
    Thanks!

    • Alex

  • in this line in comment index[3,4]

  • Thank you very much for this tutorials. They were really great. I’m an amateur game designer, do you have any references on where to go from here?

    Very much appreciated!

    • Alex

      See the other suggestions made in comments to other users. Those are still reasonable suggestions for topics.

      As for specific tutorials, I don’t have any good ones in mind.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter