Qt C++ How to chop a letter of QString that is member of a QStringList in 1 command

1.2k Views Asked by At

in my code I need to remove the last space(s) of a QString that is an element of a QStringlist DataColumns.

This is what I have:

  DataColumns[0] : "Time [ms]      "
  DataColumns[1] : "Position [m]"
  DataColumns[2] : "End Velocity [m/s]     "

This is what I want to have:

  DataColumns[0] : "Time [ms]"
  DataColumns[1] : "Position [m]"
  DataColumns[2] : "End Velocity [m/s]"

In a loop over i (element of DataColumn) and j (letter of element of DataColumn) I do the following and it works:

 QStringList dataColums;
 QString A;
 ...
 A= dataColums[i];
 A.chop(1);
 dataColums[i] = A;

But when I try to put the last 3 lines into 1 command it doesn`t work.

dataColums[i] = dataColums[i].chop(1);

Can anybody explain to my as to why that is? Thank you!

2

There are 2 best solutions below

0
Vlad from Moscow On BEST ANSWER

The function is declared like

void QString::chop(int n);

that is it has the return type void.

So this statement

dataColums[i] = dataColums[i].chop(1);

is invalid. It looks like

dataColums[i] = void;

To remove white spaces from the both sides of a string you could use the member function trimmed.

0
Andrea Ricchi On

If you just need to remove spaces you can use the QString::trimmed function!

Alternatively, you can remove all the characters after the last ] using QString::truncate combined with QString::lastIndexOf.