3

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.

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
mkreddy
  • 163
  • 3
  • 5
  • 12

3 Answers3

6

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.

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
Rud Limaverde
  • 625
  • 1
  • 9
  • 14
5

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"
Alex P
  • 1,559
  • 11
  • 23
1

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 "

vahancho
  • 20,808
  • 3
  • 47
  • 55