I'm doing a leetcode challenge to practice my c++
I am supposed to replace all the "." from an ip address to "[.]"
so essentially, xxxx is supposed to become x[.]x[.]x[.]x
My code is:
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, const char * argv[]) {
string address ="1.1.1.1";
while(address.find(".") != string::npos){
address.replace(address.find("."), 1,"[.]");
}
cout<<address<<endl;
}
However, I am getting stuck in a loop where it is doing:
xxxx
x[.]xxx
x[[.]]xxx
x[[[.]]]xxx
and so on.
How do I get out of this loop? Thank you!
You can specify where to start by the 2nd argument of std::string::find
.
#include <iostream>
#include <string>
int main(int argc, const char * argv[]) {
std::string address ="1.1.1.1";
std::string::size_type start_pos = 0, current_pos;
while((current_pos = address.find(".", start_pos)) != std::string::npos){
address.replace(current_pos, 1,"[.]");
start_pos = current_pos + 3; // start next search after the inserted string
}
std::cout<<address<<std::endl;
}
Learn to separate code into functions (this is important). Also it is easier to store result into separate variable, so you do not have to update search point.
std::string escapeDots(const std::string& s)
{
std::string result;
result.reserve(s.size() + 8);
for (auto ch : s) {
if (ch == '.')
result += "[.]";
else
result += ch;
}
return result;
}
This code is more clear the alternative answer and most probably is faster.
With <regex>
, it would be
int main()
{
std::string address = "1.1.1.1";
std::cout << std::regex_replace(address, std::regex("\\."), "[.]") << std::endl;
}
Demo .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.