Replace a part of a string

Viewed 97

Annotation: In my code I have edited the string at an adneren position, this I have not had in my example. Since here the actual error cause/problem lay I have adapted the example, see example below.

The Answer should be: std::string.resize increases the memory size of the string to the maximum expected size. replace inserts the entire size into str0.

A solution is to execute resize only if str1.lengh > max_len.

Original question:

I would like to insert a string (str1) into another (str0), at any position (n).
If str1 is shorter than the rest of string str0 (n -> str0.end()), the rest of str0 should remain.

For this I wanted to use the std::string::replace() function.

#include <string>
#include <stdint.h> 
#include <iostream>

int main()
{

    std::string str0 = "ABCDEFGHIJ";
    std::string str1 = "000";
    
    uint16_t n = 3;

    str0.replace(n, str1.length(), str1);

    std::cout << "TEST:" << str0 << std::endl;


    return 0;
 
}

In my example, I expect to output "TEST: ABC000GHIJ" via cout.

However, "TEST: ABC000" is output. Where is the problem that the string will be cutted?

Correct code example with the error cause:

#include <string>
#include <stdint.h> 
#include <iostream>

#define max_len 20

int main()
{

    std::string str0 = "ABDCDEF";
    std::string str1 = "";
    
    uint16_t n = 3;

    std::getline(std::cin, str1);

    if(!str1.empty() && str1[str1.size()-1] == '\n') {
        str1.erase(str1.size()-1);
    }
    str1.resize(max_len);

    str0.replace(n, str1.length(), str1);

    std::cout << "TEST:" << str0 << std::endl;


    return 0;
 
}
0 Answers
Related