PDA

View Full Version : QString split()



ShaChris23
2nd May 2007, 01:51
If I have a string that's delimited by 2 different delimiters, how can I use split() or something similar to split the string?

i.e.

I want to split this sentence:

$GPGGA,17.4,233.3*22 // delimiters are , and *

into

$GPGGA
17.4
233.3
22

vermarajeev
2nd May 2007, 04:19
If I have a string that's delimited by 2 different delimiters, how can I use split() or something similar to split the string?

i.e.

I want to split this sentence:

$GPGGA,17.4,233.3*22 // delimiters are , and *

into

$GPGGA
17.4
233.3
22

What about using a regular expression something like this

QRegExp rx("(\\,|\\*)");
QString str = "$GPGGA, 17.4, 233.3 * 22";
QStringList list;
int pos = 0;

while ((pos = rx.indexIn(str, pos)) != -1) {
qDebug( rx.cap(1).toLatin1().data() );
list << rx.cap(1);
pos += rx.matchedLength();
}

The above code gives the position of ',' and '*'. You can play around to get the exact string

drhex
2nd May 2007, 12:10
Checkout QString::replace() to ensure you have only one separator,
then use QString::split() to divide the string by that separator.

ShaChris23
2nd May 2007, 18:35
Here's how I did it in straight C++ with STL before. Can I do something similar in Qt?



void ParseSentence( string& mSentence,
string& mDelimiters,
vector<string>& mFields )
{
// Skip delimiters at beginning.
string::size_type lastPos = mSentence.find_first_not_of( mDelimiters, 0);
// Find first "non-delimiter".
string::size_type pos = mSentence.find_first_of( mDelimiters, lastPos);

while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
mFields.push_back( mSentence.substr( lastPos, pos - lastPos ) );
// Skip delimiters. Note the "not_of"
lastPos = mSentence.find_first_not_of( mDelimiters, pos );
// Find next "non-delimiter"
pos = mSentence.find_first_of( mDelimiters, lastPos );
}
}




example of usage:
// Parse sentence
ParseSentence( str,
string(", *"),
str_fields );

vermarajeev
3rd May 2007, 04:10
If you are happy with above code then use it directly, Qt will not complain. But take care to include appropriate header files for your STL classes. Once you are happy with what you got after parsing, then QString (a Qt string ) takes std::string as argument in one of its constructor.

Njoy