Qt之QString常用API

QString是Qt中用于处理字符串的类,接下来总结一下QString的常用API——温故而知新。

1、获取字符串长度

//字符串长度
str.length();
str.size();
str.count();

2、字符串追加

QString str="this is";

str=str+" qt";

str.append(" coding");

输出 "this is qt coding"

3、往字符串前添加,并在指定位置插入字符串

str.prepend("hello ");

//指定位置插入
str.insert(13," C++");

输出 "hello this is C++ qt coding"

4、移除指定字符串

str=str.remove("hello ");

输出 "this is C++ qt coding"

5、字符串替换

str.replace("qt","Qt");    //将qt替换为Qt
str.replace(5,2,"Is");     //将第5个位置后的两个字符替换为Is

输出 "this Is C++ Qt coding"

6、字符串查找

//判断字符串是否包含Qt
if(str.contains("Qt"))
{
   qDebug()<<"true";
}

//查找某个特定字符串或字符出现的位置
int pos=str.indexOf("Qt");
qDebug()<<pos;

输出 true 与 12

7、QString转c++的std string

str.toStdString();

8、数字转QString 与 QString 转数字

int num=2019;

str=QString::number(num);    //int类型数字 转QString字符串

int code=str.toInt(); //字符串转int类型数字

QString还提供了toDouble()、toFloat()、toLong()等数值转换接口。

9、判断字符串是否为空

if(str.isEmpty())
{
    qDebug()<<true;
}
发布了133 篇原创文章 · 获赞 175 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/c_shell_python/article/details/100068677