[笔试面试][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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值