C: Get substring before a certain char

Just put a 0 at the place of the slash

#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;
}

I don't know if this works in C++


Here is how you would do it in C++ (the question was tagged as C++ when I answered):

#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;
}

Tags:

C

String

Char