220k views
2 votes
Given string stringValue on one line, string str2 on a second line, and integer choiceLen on a third line, replace the first choiceLen characters in stringValue with the contents of str 2 . Ex: If the input is: Fuzzy bear Happ 4 then the output is: Happy bear Note: Using a pre-defined string function, the solution can be just one line of code. 1 #include 2 #include 〈string〉 3 using namespace std; 5 int main(){ 6 string stringvalue; 7 string str2; 8 int choicelen; 10 getline(cin, stringvalue); 11 getline(cin, str2); 12 cin > choicelen; 13 I * Your code goes here */ 15 cout ≪< stringValue << end

3
;

1 Answer

3 votes

Answer:

To replace the first `choiceLen` characters in `stringValue` with the contents of `str2`, we can use the `replace` function from the `<string>` library. The `replace` function takes three parameters: the starting position, the number of characters to replace, and the replacement string.

Therefore, a possible one-line solution (as indicated in the prompt) is:

```

stringvalue.replace(0, choicelen, str2);

```

This will replace the first `choicelen` characters in `stringValue` with the contents of `str2`. Then, we can output the modified string using:

```

cout << stringvalue << endl;

```

Therefore, the complete program would be:

```

#include <iostream>

#include <string>

using namespace std;

int main() {

string stringvalue;

string str2;

int choicelen;

getline(cin, stringvalue);

getline(cin, str2);

cin >> choicelen;

stringvalue.replace(0, choicelen, str2);

cout << stringvalue << endl;

return 0;

}

```

For example, if the input is:

```

Fuzzy bear

Happ

4

```

the output will be:

```

Happy bear

```

User Javier Rosa
by
8.7k points