题解:
讲address的每个字符串以
.
分隔,然后放入字符串数组,最后在除了最后一个字符串后面加入一个[.]
就可以了。
分隔是用的:strtok
函数(字符串要用char表示)
char —> string:直接强制转换
string —> char*:char* str1= const_cast<char *>(str2.c_str());
代码:
class Solution {
public:
string defangIPaddr(string address) {
char* address_Char = const_cast<char *>(address.c_str());
vector <string> vec;
char* result = NULL;
result = strtok(address_Char,".");
while(result != NULL)
{
vec.push_back((string)result);
result = strtok(NULL,".");
}
string res = "";
for(int i = 0; i < (int)vec.size(); i++)
{
res += vec[i];
if(i != (int)vec.size()-1)
res += "[.]";
}
return res;
}
};