qt获取字符串子串位置
时间: 2023-02-11 15:20:30 浏览: 130
在 Qt 中,可以使用 QString 类的 indexOf() 函数来获取字符串子串的位置。
语法如下:
```
int indexOf(const QString &str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
```
其中,str 参数表示要查找的子串,from 参数表示从哪个位置开始查找,cs 参数表示是否区分大小写。
使用方法如下:
```
QString str = "Hello, Qt!";
int pos = str.indexOf("Qt");
```
上面的代码会在字符串 str 中查找子串 "Qt",并返回其位置。如果没有找到子串,则返回 -1。
此外,还可以使用 lastIndexOf() 函数来获取字符串子串最后出现的位置。
语法如下:
```
int lastIndexOf(const QString &str, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
```
其中,str 参数、cs 参数的含义与 indexOf() 函数相同,from 参数表示从哪个位置开始查找,-1 表示从字符串末尾开始查找。
使用方法如下:
```
QString str = "Hello, Qt!";
int pos = str.lastIndexOf("Qt");
```
上面的代码会在字符串 str 中从末尾开始查找子串 "Qt",并返回其位置。如果没有找到子串,则返回 -1。