在Qt中,獲取字符串的長(zhǎng)度可以使用QString類提供的length()或size()函數(shù)。這兩個(gè)函數(shù)都用于返回字符串的長(zhǎng)度。
下面是一個(gè)示例代碼,演示如何在Qt中獲取字符串的長(zhǎng)度:
#include#include #include int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QString str = "Hello, World!"; // 使用length()函數(shù)獲取字符串的長(zhǎng)度 int length1 = str.length(); qDebug() << "Length of the string: " << length1; // 使用size()函數(shù)獲取字符串的長(zhǎng)度 int length2 = str.size(); qDebug() << "Length of the string: " << length2; return app.exec(); }
運(yùn)行該代碼將輸出:
Length of the string: 13 Length of the string: 13
這兩個(gè)函數(shù)都返回字符串的字符數(shù),包括空格和特殊字符。如果要獲取字符串中實(shí)際可見(jiàn)字符的數(shù)量(即不包含空格等特殊字符),可以使用QString的simplified()函數(shù)進(jìn)行處理。