LeetCode算法题解 1108-IP 地址无效化

题目描述

题解:

讲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;
    }
};
发布了197 篇原创文章 · 获赞 18 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41708792/article/details/104619045