How do you replace every "dicktionary" word in a text with "dictionary" using loop?
Original text: I love my dicktionary. A dicktionary helps me to improve my vocabs.
Corrected text: I love my dictionary. A dictionary helps me to improve my vocabs.
#include <iostream>
#include <string>
// replaces words in string
// - implementation was restricted to well-known members of std::string. Code can be reduced
// by using overloads of compare() and assign() members, etc.
// - this function is just an exercise. In "real life" could achieve the same effect using
// std::regex_replace() Or could use some sort of iterator/algorithm-based approach
std::string ReplaceWord(const std::string& src, const std::string& old, const std::string& replace)
{
std::string dest;
constchar non_alnum[]{ " !\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~" };
std::size_t pos_from = 0;
std::size_t pos_to = src.npos;
while (pos_from != src.npos)
{
pos_to = src.find_first_not_of(non_alnum, pos_from);
if (pos_to != src.npos)
{
std::string non_word = src.substr(pos_from, pos_to - pos_from);
dest += non_word;
pos_from = pos_to;
pos_to = src.find_first_of(non_alnum, pos_from);
size_t word_len = (pos_to == src.npos) ? src.npos : (pos_to - pos_from);
std::string word = src.substr(pos_from, word_len);
dest += (word == old) ? replace : word;
pos_from = pos_to;
}
else
{
std::string non_word = src.substr(pos_from);
dest += non_word;
pos_from = src.npos;
}
}
return dest;
}
int main()
{
std::string input("The C++ language has types int, lang, and short. It's not slang!");
std::string output = ReplaceWord(input, "lang", "long");
std::cout << "output = " << output << '\n';
}
Output:
output = The C++ language has types int, long, and short. It's not slang!