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.

A.1 -- Static and dynamic libraries
Index
17.6 -- std::string appending

8 comments to 17.7 — std::string inserting

  • 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;
    }

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

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">