22.7 — std::string 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:



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:



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:



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:



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.

23.1 -- Input and output (I/O) streams
22.6 -- std::string appending

25 comments to 22.7 — std::string inserting

  • Ayrton Fithiadi Sedjati

    Hi Alex (or nascardriver),

    I understood that in 17.1 you wrote "std::strings (and std::wstring) will be referred to simply as “strings”."

    However, would you please explain why you used the type 'std::string' *in your sample codes* up until 17.4, and changed it into just 'string' starting from 17.5?

    • nascardriver


      The lessons this far back don't get as many visitors as the early ones, so they're not maintained as good (Because people don't point out the issues). Congratulations on making it to the older part of learncpp :D I marked the lessons starting at 17.5 for an update, thanks!

      • Ayrton Fithiadi Sedjati

        You're welcome!

        I am planning to re-read this tutorial from the beginning to improve my understanding and gain more insight. It's so well-written that I don't mind reading it all over again.

        Now that I am also planning to learn the basics of PHP, I found it difficult to find a satisfactory tutorial since learncpp has set my expectation so high :D

        Thank you, nascardriver (and Alex), for this treasure and for being so active in the comment sections. It really helps many people like me. :)

      • Tomek

        How is the update going?

  • 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.

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

  • 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.

    • Alex

  • 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. :(

  • 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.

      • salah

        Hi Alex, do you have a data structure tutorial similar to this tutorial  ? honestly this course is great...thanks so much

  • Thibaut

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

  • Jackson maduranga_SAC

    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 !
    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;
    {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;
    int j;
    int k= 0;
    a[i-1].total = k;
    a[i-1].mean =(float)k/NS;
    void showoutput()
    int i,j;
    cout << " \tTOTAL\tMEAN\t\tPOSITION\n"<< endl;
    cout << "No("<<i<<")\t" << a[i-1].total << "\t" << a[i-1].mean<<"\t\t"<< a[i-1].pos<<endl;
    cout << "-------------------------------------------------------------------------"<<endl;
    void pos()
    int i,j,k;
    long int arr[50];
    int temp = arr[k];
    arr[k] = arr[k-1];
    arr[k-1] = temp;}
    // dec pos
    int m,n;
    a[n-1].pos = m;

    //cheaking purposes
    cout << "****#" << endl;
    int c;
    {cout << arr

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

    // END cheak


    void CHEAK()
    int 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;
    cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" << endl;
    cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"<<endl;
    cout << "_______________________________________________________________________________" <<endl;
    cout << " -[maduranga]-"<<endl;

    return 0;

  • X

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

  • octavsly

    :-) got replaced correctly

  • octavsly

    HTML codes broken. Example of what I see.

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

  • Skippeh

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

  • 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!

  • Sean

    "I'm baaaaaaaaack."

  • Brian

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

Leave a Comment

Put all code inside code tags: [code]your code here[/code]