Per esempio, io ho questa stringa: 10.10.10.10/16
Ottenere 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?
Per esempio, io ho questa stringa: 10.10.10.10/16
Ottenere 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?
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++
memoria sprecata! tutti e 3 i byte! – 75inchpianist
@ 75pianpianista Cosa intendi con questo? Dov'è il ricordo "sprecato" e come? –
Non dovrebbe essere '* p = '\ 0';' – stedotmartin
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
mi dispiace ma c è quello che mi serve. modificato i miei tag. – Itzik984
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;
}
Mi dispiace davvero, c è quello che mi serve – Itzik984
Esempio 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;
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';
}
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;
}
È possibile combinare 'std :: string :: substr() 'e' std :: string :: find() ' –
se stai cercando di distruggere la stringa originale, puoi usare' strchr ('/') = '\ 0'' – aragaer
puoi anche usare ' funzione memchr', quindi 'strcpy'. – Raj