Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Get substring before a certain char

Tags:

c

string

char

For example, I have this string: 10.10.10.10/16

and I want to remove the mask from that IP and get: 10.10.10.10

How could this be done?

like image 732
Itzik984 Avatar asked Feb 21 '13 15:02

Itzik984


People also ask

How do you get a substring from a string before a character?

Use the substring() method to get the substring before a specific character, e.g. const before = str. substring(0, str. indexOf('_')); . The substring method will return a new string containing the part of the string before the specified character.

How do you read a string upto a certain character in C?

Use sscanf() like this: char subStr[3]; sscanf("M1[r2][r3]", " %2[^[]", subStr); where [^[] means a character except [ and 2 guards the length of the string written into the substring (it's equal to subStr 's size - 1, so that space for the NULL terminator is available). as BLUEPIXY suggested.

How do I get the string after a specific character in CPP?

std::string x = "dog:cat"; std::string substr; auto npos = x. find(":"); if (npos != std::string::npos) substr = x.


3 Answers

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;
}
like image 92
Andy Prowl Avatar answered Oct 09 '22 18:10

Andy Prowl


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++

like image 18
pmg Avatar answered Oct 09 '22 20:10

pmg


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
like image 3
75inchpianist Avatar answered Oct 09 '22 19:10

75inchpianist