2

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!

user3443063
  • 1,455
  • 4
  • 23
  • 37
  • The operator `[]` returns a reference of the `QString`, so why don't you just do: `dataColumns[i].chop(n)` ? But yes, QString::trimmed() would be much better for your case. – Fareanor Jan 10 '20 at 10:25

2 Answers2

2

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.

Andrea Ricchi
  • 480
  • 5
  • 12
2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335