我必须改变“。”使用 C++ 将 IP 地址的一部分转换为“[.]”。示例:“1.1.1.1”应转换为“1[.]1[.]1[.]1” 我尝试使用正常的 for 循环来解决它,但它会引发错误`
它显示此错误:
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)
| ^~~~~~~~~~~~~~~~~
有人可以解释一下我在这里犯了什么错误吗?\
string defangIPaddr(string address) {
for(int i=0;i<address.size();i++)
{
if(address[i]==".")
{
address[i]="[.]";
}
}
return address;
}
错误在于
address[i]
与字符串 "."
address[i]="[.]"
。即使您修复了这些问题以使代码编译时没有错误,您的循环也非常尴尬,因为如果找到
.
,则增加原始字符串的大小,同时您的循环取决于字符串的大小字符串。
无需执行所有这些操作,只需从原始字符串构建一个新字符串即可:
#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");
}
输出:
1[.]1[.]1[.]1