Получите подстроку перед определенным char в (c)

Например, у меня есть эта строка: 10.10.10.10/16

и я хочу удалить маску из этого ip и получить: 10.10.10.10

Как это можно сделать?

Ответы

Ответ 1

Просто поместите 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;

Я не знаю, работает ли это на С++

Ответ 2

Вот как вы это сделаете в С++ (вопрос был отмечен как С++, когда я ответил):

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

Ответ 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

Ответ 4

Я вижу, что это в C, поэтому я думаю, что ваша "строка" - "char *"?
Если это так, вы можете иметь небольшую функцию, которая чередует строку и "вырезает" ее при определенном 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';
}

Ответ 5

Пример в 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;

Ответ 6

Пример в С++

#include <iostream>
using namespace std;

int main() 
{
    std::string connectionPairs("10.0.1.11;10.0.1.13");
    std::size_t pos = connectionPairs.find(";");
    std::string origin = connectionPairs.substr(0,pos);
    std::string destination = connectionPairs.substr(pos + 1);
    std::cout << origin << std::endl;
    std::cout << destination << std::endl;
    return 0;
 }