Home > Blockchain >  How to Get substring from given QString in Qt
How to Get substring from given QString in Qt

Time:01-11

I have a QString like this:

QString fileData = "SOFT_PACKAGES.ABC=MY_DISPLAY_OS:MY-Display-OS.2022-3.10.25.10086-1.myApplication"

What I need to do is to create substrings as follow:

SoftwareName = MY_DISPLAY_OS //text after ':'
Version = 10.25.10086-1
Release = 2022-3

I tried using QString QString::sliced(qsizetype pos, qsizetype n) const but didn't worked as I'm using 5.9 and this is supported on 6.0.

QString fileData = "SOFT_PACKAGES.ABC=MY_DISPLAY_OS:MY-Display-OS.2022-3.10.25.10086-1.myApplication";

QString SoftwareName = fileData.sliced(fileData.lastIndexOf(':'), fileData.indexOf('.'));

Please help me to code this in Qt.

CodePudding user response:

One way is using

QString::mid(int startIndex, int howManyChar);

so you probably want something like this:

QString fileData = "SOFT_PACKAGES.ABC=MY_DISPLAY_OS:MY-Display-OS.2022-3.10.25.10086-1.myApplication";

QString SoftwareName = fileData.mid(fileData.indexOf('.') 1, (fileData.lastIndexOf(':') - fileData.indexOf('.')-1));

To extract the other part you requested and if the number of '.' characters remains constant along all strings you want to check you can use the second argument IndexOf to find shift the starting location to skip known many occurences of '.', so for example

int StartIndex = 0;
int firstIndex = fileData.indexOf('.');
for (int i=0; i<=6; i  ) {
    StartIndex  = fileData.indexOf('.', firstIndex StartIndex);
}

int EndIndex = fileData.indexOf('.', StartIndex 8);

should give the right indices to be cut out with

QString SoftwareVersion = fileData.mid(StartIndex, EndIndex - StartIndex);

If the strings to be parsed stay less consistent in this way, try switching to regular expressions, they are the more flexible approach.

CodePudding user response:

Use QString::split 3 times:

  1. Split by QLatin1Char('=') to two parts:

    • SOFT_PACKAGES.ABC
    • MY_DISPLAY_OS:MY-Display-OS.2022-3.10.25.10086-1.myApplication
  2. Next, split 2nd part by QLatin1Char(':'), probably again to just 2 parts if there can never be more than 2 parts, so the 2nd part can contain colons:

    • MY_DISPLAY_OS
    • MY-Display-OS.2022-3.10.25.10086-1.myApplication
  3. Finally, split 2nd part of previous step by QLatin1Char('.'):

    • MY-Display-OS
    • 2022-3
    • 10
    • 25
    • 10086-1
    • myApplication

Now just assemble your required output strings from these parts. If exact number of parts is unknown, you can get Version = 10.25.10086-1 by removing two first elements and last element from the final list above, and then joining the rest by QLatin1Char('.'). If indexes are known and fixed, you can just use QStringLiteral("%1.%2.%3").arg(....

  •  Tags:  
  • c qt
  • Related