21

例如,我有这个字符串:10.10.10.10/16

我想从该 IP 中删除掩码并获得:10.10.10.10

怎么可能做到这一点?

4

6 回答 6

29

以下是您在 C++ 中的操作方式(当我回答时,问题被标记为 C++):

#include <string>
#include <iostream>

std::string process(std::string const& s)
{
    std::string::size_type pos = s.find('/');
    if (pos != std::string::npos)
    {
        return s.substr(0, pos);
    }
    else
    {
        return s;
    }
}

int main(){

    std::string s = process("10.10.10.10/16");
    std::cout << s;
}
于 2013-02-21T15:43:24.740 回答
17

只需在斜线的位置放一个 0

#include <string.h> /* for strchr() */

char address[] = "10.10.10.10/10";
char *p = strchr(address, '/');
if (!p)
{
    /* deal with error: / not present" */
    ;
}
else
{
   *p = 0;
}

我不知道这是否适用于 C++

于 2013-02-21T15:47:03.363 回答
3
char* pos = strstr(IP,"/"); //IP: the original string
char [16]newIP;
memcpy(newIP,IP,pos-IP);   //not guarenteed to be safe, check value of pos first
于 2013-02-21T15:43:09.157 回答
1

我看到这是在 C 中,所以我猜你的“字符串”是“char *”?
如果是这样,您可以使用一个小函数来交替字符串并在特定字符处“剪切”它:

void cutAtChar(char* str, char c)
{
    //valid parameter
    if (!str) return;

    //find the char you want or the end of the string.
    while (*char != '\0' && *char != c) char++;

    //make that location the end of the string (if it wasn't already).
    *char = '\0';
}
于 2013-02-21T15:48:57.933 回答
1

C++ 中的示例

#include <iostream>
using namespace std;

int main() 
{
    std::string addrWithMask("10.0.1.11/10");
    std::size_t pos = addrWithMask.find("/");
    std::string addr = addrWithMask.substr(0,pos);
    std::cout << addr << std::endl;
    return 0;
 }
于 2017-03-10T18:52:53.900 回答
0

中的示例

char ipmask[] = "10.10.10.10/16";
char ip[sizeof(ipmask)];
char *slash;
strcpy(ip, ipmask);
slash = strchr(ip, '/');
if (slash != 0)
    *slash = 0;
于 2013-02-21T15:47:33.373 回答