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?
QChar QString::front() const Returns the first character in the string. Same as at(0).
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.
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.
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.
This the syntax to remove the two first characters.
str.remove(0, 2);
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With