这次欠债比较多,所以,这次的代码风格很差。方法是最暴力的暴力求解法。
//ip restore
//if input is 19216811
//out put should be 192.168.1.1 or 19.216.8.11 or some_str available else
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LOG_FLAG 1
/*
description: API to get substring in C code
owner: howyee
*/
int substring_king(char *src,char *dst,int start,int end)
{
//memset(a,0,20*sizeof(char));
memset(dst,0,strlen(dst)*sizeof(char));
dst = strncpy(dst,src+start,end-start);
return 0;
}
int is_valid(char *sub_ip)
{
//puts(sub_ip);
if(atoi(sub_ip)>255)
return -1;
else
return 0;
}
//1.9.2.1681212
// char *strncpy(char *dest, const char *src,int count)
int ip_process(char *ip_buf , int lens_ip)
{
int i,j,k;
char buf_1[5],buf_2[5],buf_3[5],buf_4[5];
for(i=0;i<lens_ip-1;i++)
for(j=i+1;j<lens_ip-1;j++)
for(k=j+1;k<lens_ip-1;k++)
{
substring_king(ip_buf,buf_1,0,i+1);
printf("buf_1 %s atoi %d\n", buf_1 ,atoi(buf_1));
substring_king(ip_buf,buf_2,i+1,j+1);
printf("buf_2 %s atoi %d\n", buf_2 ,atoi(buf_2));
substring_king(ip_buf,buf_3,j+1,k+1);
printf("buf_3 %s atoi %d\n", buf_3 ,atoi(buf_3));
substring_king(ip_buf,buf_4,k+1,lens_ip);
printf("buf_4 %s atoi %d\n", buf_4 ,atoi(buf_4));
//if((is_valid_sub_ip(buf_1)==0)&&((is_valid_sub_ip(buf_1)==0)&&((is_valid_sub_ip(buf_1)==0)&&((is_valid_sub_ip(buf_1)==0)))
if((is_valid(buf_1)==0)&&(is_valid(buf_2)==0)&&(is_valid(buf_3)==0)&&(is_valid(buf_4)==0))
{
printf("good ip%s %s %s %s\n",buf_1,buf_2,buf_3,buf_4);
}
}
}
int test_case(char *temp_buf)
{
char temp[15];
//puts(temp);
substring_king(temp_buf,temp,0,3);
puts(temp);
substring_king(temp_buf,temp,1,2);
puts(temp);
substring_king(temp_buf,temp,2,3);
puts(temp);
substring_king(temp_buf,temp,3,5);
puts(temp);
}
int main(int argc, char **argv)
{
char ip_input[20] , temp[15];
if(argc!=2){
printf("Usage: ip_restore ip_addr\n");
//return -1;
gets(ip_input);
}
else
strcpy(ip_input,argv[1]);
#if LOG_FLAG
puts(ip_input);
//test_case(ip_input);
#endif
//max lens of ip is 12
substring_king(ip_input,temp,0,1);
puts(temp);
if(strlen(ip_input)>12)
{
printf("too long for a ip ip_addr\n");
return -1;
}
else
{
ip_process(ip_input,strlen(ip_input));
}
}