17

How would I remove the the first two characters of a QString or if I have to put it a StackOverflows layman's terms:

QString str = "##Name" //output: ##Name

to

output: Name

So far I have used this small piece of code:

if(str.contains("##"))
{
    str.replace("##","");
}

..but it doesn't work as I would need to have "##" in some other strings, but not at the beginning.

The first two characters may occur to be "%$" and "#@" as well and that mostly the reason why I need to delete the first two characters.

Any ideas?

sandwood
  • 2,038
  • 20
  • 38
Joe Carr
  • 445
  • 1
  • 10
  • 23

3 Answers3

23

This the syntax to remove the two first characters.

str.remove(0, 2); 
Kenly
  • 24,317
  • 7
  • 44
  • 60
Amd Dmb
  • 269
  • 2
  • 6
14

You can use the QString::mid function for this:

QString trimmed = str.mid(2);

But if you wish to modify the string in place, you would be better off using QString::remove as others have suggested.

paddy
  • 60,864
  • 6
  • 61
  • 103
4

You can use remove(const QRegExp &rx)

Removes every occurrence of the regular expression rx in the string, and returns a reference to the string. For example:

QString str = "##Name" //output: ##Name
    str.remove(QRegExp("[#]."));
    //strr == "Name"
Rahim
  • 146
  • 1
  • 8
  • This is not the best answer for the question but it solved my problem: I wanted to remove all occurence of a given character. – Martin Delille Nov 30 '18 at 23:04