0

I'm doing a leetcode challenge to practice my c++

I am supposed to replace all the "." from an ip address to "[.]"

so essentially, x.x.x.x 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 :

x.x.x.x

x[.]x.x.x

x[[.]]x.x.x

x[[[.]]]x.x.x

and so on.

How do I get out of this loop? Thank you!

Gabe
  • 116
  • 6
  • 2
    Remember that [`find`](https://en.cppreference.com/w/cpp/string/basic_string/find) also have an argument for starting position, where it should start looking from. – Some programmer dude Apr 19 '21 at 11:34
  • You are continually finding `.` character, even after replacing it with `[.]` – Zoso Apr 19 '21 at 11:34
  • Does this answer your question? [Parse (split) a string in C++ using string delimiter (standard C++)](https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c) – Nina Apr 19 '21 at 11:52
  • Do not do it in place, but store result to separate variable. It will be easier. – Marek R Apr 19 '21 at 11:59

3 Answers3

5

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;
}
MikeCAT
  • 61,086
  • 10
  • 41
  • 58
0

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.

Marek R
  • 23,155
  • 5
  • 37
  • 107
0

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.

Jarod42
  • 173,454
  • 13
  • 146
  • 250