0

I am new to C++ and I am trying to use the Qt framework to create an app, however, I need to parse a big text file, struggling with the split() option.

I am trying to split each line into 6 pieces, each string is not the same length, so not sure if I can use the mid(), left() or right() functions ?

For example, in Java, I can easily do it with a max split, like this, it allows me to split into 6 pieces, keep the white spaces in the last substring:

    String str = "1    689 0 0 02WA Aaaa Bbbb Ccccc";
    String str2 = "1    6389 0 0 02WAB Eeee Ff Ggggggggg";

    System.out.println("First line");
    for(int i=0; i < 6; i++){
       System.out.println(str.split("\\s+", 6)[i]);
    }
    System.out.println("\nSecond line");
    for(int i=0; i < 6; i++){
       System.out.println(str2.split("\\s+", 6)[i]);
    }

Output:

First line
1
689
0
0
02WA
Aaaa Bbbb Ccccc

Second line
1
6389
0
0
02WAB
Eeee Ff Ggggggggg

The problem is, if I knew the exact length of each sub string I want, I could use left(),right() or mid() I guess, but they change line by line, so I never know.

Is there any way I can achieve this in Qt the same as Java does ?

  • See https://stackoverflow.com/questions/18343253/qt-qstring-maxsplit-argument for the answer. – dom0 Aug 11 '18 at 20:24
  • Possible duplicate of [Qt QString maxsplit argument](https://stackoverflow.com/questions/18343253/qt-qstring-maxsplit-argument) – dom0 Aug 11 '18 at 20:25
  • I have seen that one, but as I mentioned, to use the QString::mid (left or right) function, you need to know the _n_ number of characters: QString QString::mid(int position, int n = -1) const Returns a string that contains _n_ characters of this string, starting at the specified position index. The issue is, I don't know how long the string is, or sub strings are that I need, I just need to split by "whitespace" for the first 5 times, then give me the rest as the 6th split. – m0ng00se Aug 12 '18 at 03:55
  • Ah right. You can use QString::indexOf to determine the position of the first whitespace, then use QString::mid() (or ::left) to extract the first substring. Then use ::indexOf() again (with the `from` argument set to the last position, possibly +1) to determine the next position and use ::mid() again to extract it. You can write this in a for() loop to split *n* times. Remember to exit the loop if indexOf() returns -1. – dom0 Aug 12 '18 at 10:15
  • nice ..I am going to look at that or just make a little java program to do the parsing for me ;) thanks – m0ng00se Aug 12 '18 at 19:39

0 Answers0