九度-题目1203:IP地址

http://ac.jobdu.com/problem.php?pid=1203

题目描述:

    输入一个ip地址串,判断是否合法。

输入:

    输入的第一行包括一个整数n(1<=n<=500),代表下面会出现的IP地址的个数。
    接下来的n行每行有一个IP地址,IP地址的形式为a.b.c.d,其中a、b、c、d都是整数。

输出:

    可能有多组测试数据,对于每组数据,如果IP地址合法则输出"Yes!”,否则输出"No!”。

样例输入:
2
255.255.255.255
512.12.2.3
样例输出:
Yes!
No!
提示:

合法的IP地址为:
a、b、c、d都是0-255的整数。

来源:
2006年华中科技大学计算机保研机试真题
解1:
根据.的位置直接判断,输入的格式是确定的。只要判断四个数字的正确性。
 1 #include<stdio.h>
 2 #include<string.h>
 3 
 4 int main() {
 5     int n;
 6     while (scanf("%d", &n) != EOF) {
 7         while (n--) {
 8             char ip[100];
 9             scanf("%s", ip);
10             int len = strlen(ip);
11             int count = 0;
12             int num = 0;
13             for (int i = 0; i < len; i++) {
14                 if (ip[i] == '.') {
15                     if (num >= 0 && num <= 255) {
16                         count++;
17                     }
18                     num = 0;
19                 } else {
20                     num = num * 10 + ip[i] - '0';
21                 }
22             }
23             if (num >= 0 && num <= 255) {
24                 count++;
25             }
26             if (count == 4) {
27                 printf("Yes!
");
28             } else {
29                 printf("No!
");
30             }
31         }
32     }
33     return 0;
34 }

解2:

C++中没有split(分割字符串)函数。因此可以构造一个。使用起来就比较方便。不过对于该题而言,这样略显复杂。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <string>
 5 #include <vector>
 6 
 7 
 8 using namespace std;
 9 
10 
11 char ip[16];
12 
13 void split(const string& s, const string& c, vector<string>& v)
14 {
15   string::size_type last, index;
16   index = s.find(c);
17   last = 0;
18   while(string::npos != index)
19   {
20     v.push_back(s.substr(last, index-last));
21 
22     last = index + c.size();
23     index = s.find(c, last);
24   }
25   if(last != s.length())
26     v.push_back(s.substr(last));
27 }
28 
29 bool isValid(char str[], vector<string> &ret)
30 {
31     int len=strlen(str);
32     if(len>15) return false;
33 
34     string s=str;
35     string delim=".";
36 
37 
38     split(s, delim, ret);
39 
40     int size=ret.size();
41     for(int i=0; i<size; i++)
42     {
43         int num=atoi(ret[i].c_str());
44         if(num<0 || num>255)
45             return false;
46     }
47 
48     return true;
49 }
50 
51 
52 int main()
53 {
54     vector<string> ret;
55     int n;
56     while(scanf("%d", &n)!=EOF)
57     {
58         while(n--)
59         {
60             if(ret.empty()!=true)
61                 ret.clear();
62             scanf("%s", ip);
63             bool isip=isValid(ip, ret);
64             if(isip)
65                 printf("Yes!
");
66             else
67                 printf("No!
");
68         }
69     }
70 
71     return 0;
72 }
原文地址:https://www.cnblogs.com/shenckicc/p/6776172.html