Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the first two characters of a QString

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?

like image 401
Joe Carr Avatar asked Mar 07 '17 13:03

Joe Carr


People also ask

How do you get the first character of QString?

QChar QString::front() const Returns the first character in the string. Same as at(0).

How can I remove last character from QString QT?

You have QString::chop() for the case when you already know how many characters to remove. It is same as QString::remove() , just works from the back of string. Show activity on this post. You should check int pos for -1 to be sure the slash was found at all.

How do you remove the last character of a string in C++?

The C++ string class has many member functions. Two of them are the pop_back() and the erase() functions. The pop_back() function removes the last element from the string. The erase() function can erase an element anywhere in the string.


Video Answer


3 Answers

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.

like image 62
paddy Avatar answered Oct 11 '22 02:10

paddy


This the syntax to remove the two first characters.

str.remove(0, 2); 
like image 27
PLAYBOY Avatar answered Oct 11 '22 03:10

PLAYBOY


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"
like image 22
Rahim Avatar answered Oct 11 '22 02:10

Rahim