Reputation: 16764
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?
Upvotes: 24
Views: 90121
Reputation: 108938
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++
Upvotes: 19
Reputation: 440
Example in 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;
}
Upvotes: 1
Reputation: 4102
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
Upvotes: 4
Reputation: 74028
Example in c
char ipmask[] = "10.10.10.10/16";
char ip[sizeof(ipmask)];
char *slash;
strcpy(ip, ipmask);
slash = strchr(ip, '/');
if (slash != 0)
*slash = 0;
Upvotes: 0
Reputation: 19445
I see this is in C so I guess your "string" is "char*"?
If so you can have a small function which alternate a string and "cut" it at a specific 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';
}
Upvotes: 0
Reputation: 126432
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;
}
Upvotes: 36