【问题标题】:Convert an input string to Ip address format将输入字符串转换为 IP 地址格式
【发布时间】:2013-12-14 21:02:24
【问题描述】:

我正在以字符串格式从数据库中读取 IP 地址,但我想以 IP 格式显示它们,例如 192.168.100.155

char formatAs_Ipaddress(const char *str)

此函数将以IP地址的形式将传递给它的字符串格式化,即255001001001将返回为255.1.1.1

我可以获得更优化的查询方式吗?

【问题讨论】:

  • 您的确切输入是什么?什么是字符串格式,什么是 IP 格式?
  • 这里我正在考虑一个 Ipv4 地址输入字符串,类似于 192168010010,我的预期输出是 192.168.10.10
  • 为什么将问题标记为C++并提出C风格的解决方案?
  • @abyss,我一直在寻找 C/C++ 的可能性。因此标记为 C++。请建议您是否有更优化的解决方案。谢谢。

标签: c string ip-address string-formatting string-parsing


【解决方案1】:

我试过这样做,它对我有用。

char formatAs_Ipaddress(const char* str)    {
    char getval;
    if(str!=0)  {
        char temp[256]; memset(temp,0,256);
        int len = strlen(str);
        int cnt = 0;
        for(int i=0,j=0;i<len;++i)  {
            temp[j] = str[i];
            if(i>=11)   {
                break;
            }
            ++j;
            ++cnt;
            if(cnt!=0 && cnt%3==0)  {
                temp[j]='.';
                ++j;
            }
        }
        getval  = temp;
    }
    return getval;
}

【讨论】:

    【解决方案2】:
    char *format_ipaddress(const char *input, char *output, int size) 
    {
        if (input == NULL || output == NULL || size < 16) // invalid parameters
            return NULL;
    
        int len = strlen(input);
        if (len != 12) // input looks invalid
            return NULL;
    
        char *outptr = output;
        for(int i = 0; i <= 9; i += 3)
        {
            char *inptr = input + i;
            int inlen = 3;
            while (inlen > 1 && *inptr == '0')
            {
               // remove zeros at beginning of subnet block
               ++inptr;
               --inlen;
            }
    
            memcpy(outptr, inptr, inlen);
            outptr += inlen; 
    
            if (i < 9)
               *outptr++ = '.';
        }
        *outptr = 0; // ensure output ends with a \0
    
        return output;
    }
    
    
    char *input = "192168010010";
    char output[16];
    char *result;
    
    result = format_ipaddress(input, output, sizeof(output));
    if (result != NULL)
    {
        printf("'%s' formated as ip address: '%s'", input, result);
    }
    else
    {
        printf("Something went wrong. Check your input.\n");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2019-05-13
      相关资源
      最近更新 更多