Search code examples
c++strcmp

Stuck with the part of string comparison


I have to change the "." parts of the IP address to "[.]" using C++. For example: "1.1.1.1" should be converted to "1[.]1[.]1[.]1".

I tried to solve it using normal for-loop,

string defangIPaddr(string address) {
    for(int i=0;i<address.size();i++)
    {
        if(address[i]==".")
        {
            address[i]="[.]";
        }
    }
    return address;
}

But it throws an error:

Line 6: Char 16: error: no matching function for call to 'strcmp'
6 |             if(strcmp(address[i],"."))
  |                ^~~~~~
/usr/include/string.h:156:12: note: candidate function not viable: no known conversion from 'value_type' (aka 'char') to 'const char *' for 1st argument; take the address of the argument with &
147 | extern int strcmp (const char *__s1, const char *__s2)
    |            ^~~~~~~~~~~~~~~~~

Can someone please explain what mistake(s) have I made here?


Solution

  • The errors are that

    1. You are trying to compare a single character address[i] to a string "."
    2. You are trying to stuff four characters into a single character, address[i]="[.]".

    Even if you fix those errors so that your code compiles cleanly, your loop is very awkward in that you are increasing the size of the original string if . is found, and at the same time you're looping depending on the size of the string.

    Instead of all of this, simply build a new string from the original string by looping over the original string and checking each character to see if it is '.':

    #include <string>
    #include <iostream>
    
    std::string defangIPaddr(std::string address) 
    {
        std::string newString;
        for(auto ch : address)
        {
            if (ch == '.')
                newString += "[.]";
            else
                newString += ch;
        }
        return newString;
    }
    
    
    int main()
    {
        std::cout << defangIPaddr("1.1.1.1");
    }
    

    Output:

    1[.]1[.]1[.]1