Qt中QString自定义字符截断实现方法问询及功能建议
Great question! It’s definitely a bit frustrating that QString doesn’t have built-in ltrim()/rtrim() methods for trimming arbitrary characters, unlike many other programming languages. Let’s walk through how to implement this with Qt’s existing tools, how regex can help, and then dive into your suggestion for the Qt team.
Using Existing QString APIs
The most straightforward approach is to leverage QString’s core methods to manually locate the boundaries of non-trimmed characters. Here’s a practical implementation:
// Trim leading characters from the left QString ltrim(const QString& str, const QByteArray& chars) { int startPos = 0; while (startPos < str.length() && chars.contains(str.at(startPos).toLatin1())) { startPos++; } return str.mid(startPos); } // Trim trailing characters from the right QString rtrim(const QString& str, const QByteArray& chars) { int endPos = str.length() - 1; while (endPos >= 0 && chars.contains(str.at(endPos).toLatin1())) { endPos--; } return str.left(endPos + 1); } // Trim both leading and trailing characters QString trimmed(const QString& str, const QByteArray& chars) { return rtrim(ltrim(str, chars), chars); }
How this works:
- For
ltrim(), we loop from the start of the string until we find the first character that’s not in your target character set, then usemid()to extract the substring from that position onward. - For
rtrim(), we loop backward from the end of the string until we find the last non-target character, then useleft()to get the substring up to that position. - The combined
trimmed()just chains the two functions to handle both ends at once.
Note: If you need to trim Unicode characters (not just Latin-1), swap the QByteArray parameter for a QString and adjust the check to use chars.contains(str.at(pos)) instead.
Using Regular Expressions
If you prefer a more concise solution, Qt’s QRegularExpression can handle this cleanly. The key is to target leading/trailing character groups and replace them with an empty string:
// Trim leading characters via regex QString ltrimRegex(const QString& str, const QByteArray& chars) { QString escapedChars = QRegularExpression::escape(QString::fromLatin1(chars)); QRegularExpression re("^[" + escapedChars + "]+"); return str.replace(re, ""); } // Trim trailing characters via regex QString rtrimRegex(const QString& str, const QByteArray& chars) { QString escapedChars = QRegularExpression::escape(QString::fromLatin1(chars)); QRegularExpression re("[" + escapedChars + "]+$"); return str.replace(re, ""); } // Trim both ends via regex QString trimmedRegex(const QString& str, const QByteArray& chars) { return rtrimRegex(ltrimRegex(str, chars), chars); }
Critical detail:
We use QRegularExpression::escape() to handle any regex special characters (like [, ], ^, or $) that might be in your target character set. Without this, the regex could break or match unintended characters.
Suggestion for Qt Official Team
Your proposal to add dedicated ltrim()/rtrim() methods and an overload of trimmed() to QString is spot-on. Right now, the default trimmed() only handles whitespace, which is limiting when you need to trim custom characters (like quotes, commas, or delimiters).
The function definitions you suggested are a great starting point:
QString ltrim(QByteArray &chars); // Trim left QString rtrim(QByteArray &chars); // Trim right QString trimmed(QByteArray &chars); // Trim both ends
To make this even more Qt-friendly (and Unicode-compliant), it would be ideal to also add overloads that accept QString as the character set parameter—since QString is designed for full Unicode support, unlike QByteArray which is Latin-1 focused.
These additions would align QString with common developer expectations from languages like Python, PHP, and JavaScript, reducing friction when porting code or switching between ecosystems.
Hope these workarounds get you up and running for now, and it’d be fantastic to see Qt adopt these handy methods officially in a future release!
内容的提问来源于stack exchange,提问作者Aleksey Kontsevich

