Qt入门-字符串类QString

    QString是Unicode字符的集合,它是Qt API中使用的字符串类。

    QString的成员是QChar,QChar是一个16位Unicode字符类。大多数编译器把它看作是一个unsigned short。

    QString和C标准中的字符串不同,它不以'\0'结尾,相反,QString可以嵌入'\0'/字符。

    

(1)QString初始化。

QString str("Hello");

QString str = "Hello";

static const QChar data[4] = { 0x0055, 0x006e, 0x10e3, 0x03a3 };
QString str(data, 4);

QString str;
str.resize(4);

str[0] = QChar('U');
str[1] = QChar('n');
str[2] = QChar(0x10e3);
str[3] = QChar(0x03a3);

QString str;
str.sprintf("%s %.3f", "float", 3.1415926);
//str结果是"float 3.14"

QString str;
str.setNum(10);  //str = "10"
str.setNum(10, 16); //str = "a"
str.setNum(10.12345); //str = "10.12345"

QString i;           // current file's number
QString total;       // number of files to process
QString fileName;    // current file's name

QString status = QString("Processing file %1 of %2: %3")
                     .arg(i).arg(total).arg(fileName);


(2)字符串转换

long	toLong ( bool * ok = 0, int base = 10 ) const
qlonglong	toLongLong ( bool * ok = 0, int base = 10 ) const
short	toShort ( bool * ok = 0, int base = 10 ) const
double	toDouble ( bool * ok = 0 ) const
float	toFloat ( bool * ok = 0 ) const
uint	toUInt ( bool * ok = 0, int base = 10 ) const
ulong	toULong ( bool * ok = 0, int base = 10 ) const
qulonglong	toULongLong ( bool * ok = 0, int base = 10 ) const
ushort	toUShort ( bool * ok = 0, int base = 10 ) const
参数ok结果说明转换是否成功。
示例:

	QString str;
	bool ok;  
	double d = str.toDouble(&ok);  
	if(ok)  
	{  
		cout << str << endl;  
	} else
	{
		cout << "error." << endl;
	}


(3)字符串比较

int	compare ( const QString & other ) const
int	compare ( const QString & other, Qt::CaseSensitivity cs ) const
int	compare ( const QLatin1String & other, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
int	compare ( const QStringRef & ref, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const

     QString().isNull();               // returns true
     QString().isEmpty();              // returns true

     QString("").isNull();             // returns false
     QString("").isEmpty();            // returns true

     QString("abc").isNull();          // returns false
     QString("abc").isEmpty();         // returns false

(4)字符串处理

QString left ( int n ) const  //取左边的n个字符。
QString right ( int n ) const //取右边的n个字符。

replace()函数提供方法替换字符串。

remove()函数从字符串中移除字符。

split()函数拆分字符串。

mid()取子串。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值