How to parse QString
-
I have a function
uint32_t IsIP (char *str) { int segs = 0; /* Segment count. */ int chcnt = 0; /* Character count within segment. */ int accum = 0; /* Accumulator for segment. */ size_t len = strlen(str); if (len < 7 || len > 15) return 0; /* Catch NULL pointer. */ if (str == nullptr) return 0; /* Process every character in string. */ while (*str != '\0') { /* Segment changeover. */ if (*str == '.') { /* Must have some digits in segment. */ if (chcnt == 0) return 0; /* Limit number of segments. */ if (++segs == 4) return 0; /* Reset segment values and restart loop. */ chcnt = accum = 0; str++; continue; } /* Check numeric. */ if ((*str < '0') || (*str > '9')) return 0; //prevent leading zeros if ((chcnt > 0) && (accum == 0)) return 0; /* Accumulate and check segment. */ if ((accum = accum * 10 + *str - '0') > 255) return 0; /* Advance other segment specific stuff and continue loop. */ chcnt++; str++; } /* Check enough segments and enough characters in last segment. */ if (segs != 3) return 0; if (chcnt == 0) return 0; /* Address okay. */ return 1; }
but my system variable is a QString type - QString local_ip;
On castIsIP (static_cast<char *>(local_ip))
I get an error. How can I work with a QString argument? Otherwise I have to rewrite a lot of functions.
Some of it present like QString(str).toLower() or QString(str).startWith() but still some specific functions unavailable. -
Either directly use a const char* or QByteArray or convert it with e.g. QString::toLatin1() or any other maybe more suitable conversion function you can find in the documentation.
-
@jenya7 said in How to parse QString:
IsIP (static_cast<char *>(local_ip))
As you should know,
QString
stored internally as UTF-8.
If you want an ASCII string you have to convert it:QByteArray b = local_ip.toLatin1(); IsIP(b.constData());
But perhaps you should take a look at
QHostAddress
to check your IP validity:QHostAddress ip(local_ip): if (QAbstractSocket::IPv4Protocol == ip.protocol()) { qDebug() << "Is valid IPV4 address"; }
-
Hi,
Beside the good point of @Christian-Ehrlicher, do you realize that:
@jenya7 said in How to parse QString:
IsIP (static_cast<char *>(local_ip))
is just wrong.
static_cast does no transformation at all. You are telling your compiler to access a QString object on the stack as if it were a pointer to a char on the heap. So it's a bit like telling someone to drive a bike on the ground while in fact it's a plane over the clouds.