2013-02-21 22 views
15

Per esempio, io ho questa stringa: 10.10.10.10/16Ottenere sottostringa prima di una certa char a (c)

e voglio togliere la maschera da quella IP e ottenere: 10.10.10.10

Come potrebbe questo essere fatto?

+6

È possibile combinare 'std :: string :: substr() 'e' std :: string :: find() ' –

+0

se stai cercando di distruggere la stringa originale, puoi usare' strchr ('/') = '\ 0'' – aragaer

+0

puoi anche usare ' funzione memchr', quindi 'strcpy'. – Raj

risposta

12

Basta mettere uno 0 al posto della barra

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

non so se questo funziona in C++

+7

memoria sprecata! tutti e 3 i byte! – 75inchpianist

+1

@ 75pianpianista Cosa intendi con questo? Dov'è il ricordo "sprecato" e come? –

+0

Non dovrebbe essere '* p = '\ 0';' – stedotmartin

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

mi dispiace ma c è quello che mi serve. modificato i miei tag. – Itzik984

16

Ecco come si dovrebbe fare in C++ (la questione è stata etichettata come C++ quando ho risposto):

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

Mi dispiace davvero, c è quello che mi serve – Itzik984

0

Esempio in

char ipmask[] = "10.10.10.10/16"; 
char ip[sizeof(ipmask)]; 
char *slash; 
strcpy(ip, ipmask); 
slash = strchr(ip, '/'); 
if (slash != 0) 
    *slash = 0; 
1

Vedo che questo è in C quindi immagino che la "stringa" sia "char *"?
Se così si può avere una piccola funzione che si alternano una stringa e "taglio" che ad una specifica 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'; 
} 
0

Esempio in C++

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