成员函数

1)int size() const
返回列表中元素的数量。

2)void append(const QString &str)
在列表末尾添加一个字符串。

3)void prepend(const QString &str)
在列表开头添加一个字符串。

4)void insert(int index, const QString &str)
在指定位置插入一个字符串。

5)void removeAt(int index)
移除指定位置的字符串。

6)void clear()
清空列表。

7)QString at(int index) const
返回指定位置的字符串。

8)QString first() const
返回第一个字符串。

9)QString last() const
返回最后一个字符串。

10)QString value(int index) const
返回指定位置的字符串,与 at() 函数功能相同。

11)int indexOf(const QString &str, int from = 0) const
返回字符串在列表中的索引位置,从指定位置开始搜索。

12)int indexOf(const QStringRef &str, int from = 0) const
返回字符串在列表中的索引位置,从指定位置开始搜索,使用 QStringRef 类型进行匹配。

13)bool contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
判断列表是否包含指定字符串。

14)bool contains(const QStringRef &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
判断列表是否包含指定字符串,使用 QStringRef 类型进行匹配。

15)QStringList filtered(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive, int mode = Qt::MatchContains) const
返回包含指定字符串的过滤后的列表。

16)QStringList filtered(const QRegExp &regexp, int mode = Qt::MatchContains) const
返回匹配正则表达式的过滤后的列表。

17)QString join(const QString &sep) const
使用指定的分隔符将列表中的字符串连接起来并返回连接后的字符串。

18)QString join(const QStringRef &sep) const
使用指定的分隔符将列表中的字符串连接起来并返回连接后的字符串,使用 QStringRef 类型进行匹配。

19)QString join(const QChar &sep) const
使用指定的字符将列表中的字符串连接起来并返回连接后的字符串。

20)QString join(QLatin1String sep) const
使用指定的字符将列表中的字符串连接起来并返回连接后的字符串,使用 QLatin1String 类型进行匹配。

21)QByteArray join(const QByteArray &sep) const
使用指定的分隔符将列表中的字符串连接起来并返回连接后的字节数组。

22)QList toList() const
将列表转换为字节数组列表并返回。

23)QSet toSet() const
将列表转换为字符串集合并返回。

24)bool isEmpty() const
判断列表是否为空。

常见用法

1)创建 QStringList 对象:

QStringList list;  // 创建一个空的字符串列表  
QStringList list1("Hello");  // 创建一个包含单个字符串的字符串列表  
QStringList list2("Hello", "World");  // 创建一个包含两个字符串的字符串列表  
QStringList list3 = QStringList() << "Hello" << "World";  // 使用 << 运算符创建字符串列表

2)添加和删除元素:

list.append("Hello");  // 在列表末尾添加字符串  
list.prepend("World");  // 在列表开头添加字符串  
list.insert(1, "Qt");  // 在指定位置插入字符串  
list.removeAt(1);  // 移除指定位置的字符串  
list.clear();  // 清空列表

3)访问元素:

QString str = list.at(0);  // 返回指定位置的字符串,如果越界会抛出异常  
QString first = list.first();  // 返回第一个字符串,如果列表为空则返回空字符串  
QString last = list.last();  // 返回最后一个字符串,如果列表为空则返回空字符串

4)查找和过滤:

int index = list.indexOf("Hello");  // 返回字符串在列表中的索引位置,如果未找到则返回 -1  
bool contains = list.contains("Hello");  // 判断列表是否包含指定字符串  
QStringList filtered = list.filtered("Hello");  // 返回包含指定字符串的过滤后的列表

5)连接和拆分:

QString joined = list.join(", ");  // 使用指定的分隔符将列表中的字符串连接起来并返回连接后的字符串  
QStringList split = joined.split(", ");  // 使用指定的分隔符将字符串拆分成字符串列表
转换:

QList<QByteArray> byteList = list.toList();  // 将列表转换为字节数组列表并返回  
QSet<QString> stringSet = list.toSet();  // 将列表转换为字符串集合并返回
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐