[笔试面试][code_by_hand]将字符串分割为ip地址

一个全是数字的字符串,中间插入3个.,将这个字符串分割为合法的ip地址。比如:字符串1000050000221,可以分割成1.00005.0.000221。

思路:实现一个函数CutString,每次从字符串截取下一个数字,如果这个数字小于255,就继续进行下一段ip地址的截取。否则结束。

代码中为了测试,没有很好的

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 #include <cstdlib>
 5 using namespace std;
 6 
 7 #define IP_SIZE 4
 8 
 9 string s = "1000050000221";//测试字符串
10 
11 void CutString(string str, vector<int> & ip) {
13         if (str == "" && ip.size() == IP_SIZE) {
14                 string temp = s;
15                 for (int i = 0; i < IP_SIZE; i++) {
16                         if (i > 0) {
17                                 cout << ", ";
18                         }
19                         cout << temp.substr(0, ip[i]);
20                         temp = temp.substr(ip[i], temp.length());
21                 }
22                 cout << endl;
23         }
24         if (ip.size() == IP_SIZE) {
25                 return;
26         }
27         for (int i = 1; i <= str.length(); i++) {
28                 string cutted = str.substr(0, i);
29                 string left = str.substr(i, str.length());
31                 int num = atoi(cutted.c_str());
32                 if (num > 255) {
33                         break;
34                 }
35                 ip.push_back(cutted.length());
36                 CutString(left, ip);
37                 ip.pop_back();//回溯
38         }
39 }
40 void test() {
41         string str = "12";
42         str = str.substr(str.length(), str.length());
43         if (str == "") {
44                 cout << "str is blank string" << endl;
45         }else{
46                 cout << "str is null" << endl;
47         }
48 }
49 
50 int main() {
51 //      test();
52         vector<int> tmp;
53         CutString(s, tmp);
54         return 0;
55 }
原文地址:https://www.cnblogs.com/wendelhuang/p/3391102.html