"Disclaimer: This article is limited to self-summary and mutual exchange, there are flaws also hope you point out." Contact e-mail: [Email protected] "
Topic:
IP legality Check
Topic Analysis:
(1) The string contains only numbers and '. '
(2) length between 7-15 (0.0.0.0--255.255.255.255)
(3) Each number is between 0-255
(4) '. ' No more than 3, and cannot be continuously
Algorithm implementation:
#include <stdio.h> #include <string.h> #define Max_len//255.255.255.255#define min_len 7//0.0.0.0int str _to_int (const char *begin, const char *end) {int total = 0; const char *s = BEGIN; while (s < end) {total = 10*total + (*s-' 0 '); s++; } printf ("total=%d\n", total); return total;} /*** IP Legality Check * * (1) string contains only numbers and '. ' * * (2) length between 7-15 (0.0.0.0--255.255.255.255) * * (3) Each number is between 0-255 * * (4) '. ' The number cannot be more than 3 and cannot be consecutive */int check_ip (const char *str) {int len = strlen (str); if (!str | | len > Max_len | | len < min_len) return 0; const char *slow = str, *fast = str; int Count_dot = 0, tmp; while (*fast! = ')} {if (*fast! = ') ' && (*fast < ' 0 ' | | *fast > ' 9 ')) return 0; while (*fast! = '. ') {if (*fast = = ') ' break; fast++; } if (*fast = = '. ') {if (++count_dot > 3)//. The number is greater than 3 return 0; } if (*fast = = '. ' && *slow = = '. ') Two. return 0 next to each other; TMP = Str_to_int (slow, fast); if (tmp < 0 | | tmp > 255) return 0; slow = ++fast; } return 1;} int main () {char str[] = "01.16"; Char str[] = "01.168.1.2"; Char str[] = "01.168..2"; Char str[] = "192.168.2.1000"; printf ("-------->%d\n", Check_ip (str));}
Data structure--algorithm (039) (IP legality check)