Replace the last word of a string with number
Table of Contents
C++ Code for Replace the last word of a string with number
#include <iostream>
#include <string>
int main() {
std::string str = "The quick brown fox";
std::string new_word = "42";
size_t last_space = str.find_last_of(" ");
str.replace(last_space + 1, str.size() - last_space, new_word);
std::cout << str << std::endl;
return 0;
}
Output:
The quick brown 42
Replace the first word of a string with a number in C++
#include <iostream>
#include <string>
int main() {
std::string str = "The quick brown fox";
std::string new_word = "42";
size_t first_space = str.find_first_of(" ");
str.replace(0, first_space, new_word);
std::cout << str << std::endl;
return 0;
}
Output:
42 quick brown fox