Reputation: 163
I want to get first word of a Qstring
.
For example String1 = "Read from file1"
. I want to extract string2 = "Read"
.
I want to extract substring based on whitespace.
If I encounter a first whitespace in my string1
, I need that part of string1
to string2
.
Upvotes: 3
Views: 12683
Reputation: 1609
Use QString::split
if you want to use all the parts, or QString::section
if you just want to grab the first word.
For example, the most basic syntax is:
QString str = "Do re mi";
QString firstWord = str.section(" ", 0, 0);
// firstWord = "Do"
If you need to handle all kinds of weird whitespace, you can use the regex version of the functions:
QString str = "\tDo re\nmi"; // tabs and newlines and spaces, oh my!
QString firstWord = str.section(QRegExp("\\s+"), 0, 0,
QString::SectionSkipEmpty);
// firstWord = "Do"
Upvotes: 5
Reputation: 686
Use the split function of QString
in this way:
QString firstWord = string1.split(" ").at(0);
If there is no whitespace in the string, the whole string will be returned.
Upvotes: 6
Reputation: 21240
I would do:
QString s("Read from file1");
QString subStr = s.section(" ", 0, 0, QString::SectionSkipEmpty);
This will work correctly in case of such strings too:
" Read from file1 "
Upvotes: 1