在(c)中的某个字符之前获取子字符串

Itz*_*984 17 c string char

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

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

怎么可以这样做?

And*_*owl 17

以下是如何在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;
}
Run Code Online (Sandbox Code Playgroud)


pmg*_*pmg 16

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

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

char address[] = "10.10.10.10/10";
char *p = strchr(address, '/');
if (!p) /* deal with error: / not present" */;
*p = 0;
Run Code Online (Sandbox Code Playgroud)

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

  • 浪费记忆!它的全部3个字节! (8认同)
  • @Shutupsquare:除了源代码形式外,“\0”和“0”完全相同。第一个是文字字符:它的类型为 `int`,值为 `0`;第二个是文字整数:它的类型为“int”,值为“0”。*在 C++ 中情况可能有所不同。我不懂那种语言。* (2认同)