Qt 字符串类应用

Qt 字符串类应用

在 Qt 中,字符串类 QString 是一个非常强大且常用的类,用于处理 Unicode 字符串。QString 提供了丰富的功能,包括字符串操作、格式化、转换等。
以下是一些常见的 QString 应用示例:

1. 创建和初始化 QString

#include <QString>

int main() {
    // 创建一个空的 QString
    QString emptyString;

    // 使用字符串字面量初始化 QString
    QString str = "Hello, World!";

    // 使用 fromUtf8 方法初始化 QString
    QString utf8String = QString::fromUtf8("你好,世界!");

    return 0;
}

2. 字符串连接

#include <QString>
#include <QDebug>

int main() {
    QString str1 = "Hello";
    QString str2 = "World";

    // 使用 + 运算符连接字符串
    QString result = str1 + " " + str2;
    qDebug() << result;  // 输出: "Hello World"

    // 使用 append 方法连接字符串
    str1.append(" ").append(str2);
    qDebug() << str1;  // 输出: "Hello World"

    return 0;
}

3. 字符串格式化

#include <QString>
#include <QDebug>

int main() {
    int number = 42;
    QString str = QString("The answer is %1").arg(number);
    qDebug() << str;  // 输出: "The answer is 42"

    // 格式化多个参数
    QString name = "Alice";
    int age = 30;
    QString formattedStr = QString("Name: %1, Age: %2").arg(name).arg(age);
    qDebug() << formattedStr;  // 输出: "Name: Alice, Age: 30"

    return 0;
}

4. 字符串长度和访问字符

#include <QString>
#include <QDebug>

int main() {
    QString str = "Hello";

    // 获取字符串长度
    int length = str.length();
    qDebug() << "Length:" << length;  // 输出: "Length: 5"

    // 访问字符
    QChar ch = str.at(1);
    qDebug() << "Second character:" << ch;  // 输出: "Second character: e"

    // 修改字符
    str[0] = 'h';
    qDebug() << str;  // 输出: "hello"

    return 0;
}

5. 字符串查找和替换

#include <QString>
#include <QDebug>

int main() {
    QString str = "Hello, World!";

    // 查找子字符串
    int index = str.indexOf("World");
    qDebug() << "Index of 'World':" << index;  // 输出: "Index of 'World': 7"

    // 替换子字符串
    QString replacedStr = str.replace("World", "Qt");
    qDebug() << replacedStr;  // 输出: "Hello, Qt!"

    return 0;
}

6. 字符串分割和连接

#include <QString>
#include <QStringList>
#include <QDebug>

int main() {
    QString str = "apple,banana,cherry";

    // 分割字符串
    QStringList list = str.split(",");
    qDebug() << list;  // 输出: ("apple", "banana", "cherry")
    //牛逼
    // 连接字符串
    QString joinedStr = list.join("; ");
    qDebug() << joinedStr;  // 输出: "apple; banana; cherry"

    return 0;
}

7. 字符串转换

#include <QString>
#include <QDebug>

int main() {
    QString str = "42";

    // 转换为整数
    int number = str.toInt();
    qDebug() << "Number:" << number;  // 输出: "Number: 42"

    // 整数转换为字符串
    QString newStr = QString::number(number);
    qDebug() << newStr;  // 输出: "42"

    return 0;
}

8.判断子字符串是否存在

#include <QString>
#include <QDebug>

int main() {
    QString str = "Hello, World!";

    // 判断是否包含子字符串 "World"
    bool containsWorld = str.contains("World");
    qDebug() << "Contains 'World':" << containsWorld;  // 输出: "Contains 'World': true"

    // 判断是否包含不存在的子字符串 "Qt"
    bool containsQt = str.contains("Qt");
    qDebug() << "Contains 'Qt':" << containsQt;  // 输出: "Contains 'Qt': false"

    return 0;
}

9. 使用正则表达式查询

#include <QString>
#include <QRegExp>
#include <QDebug>

int main() {
    QString str = "Hello, World! Hello, Qt!";

    // 使用 QRegExp 查找所有匹配的子字符串
    QRegExp rx("Hello");
    int pos = 0;
    while ((pos = rx.indexIn(str, pos)) != -1) {
        qDebug() << "Found 'Hello' at index:" << pos;
        pos += rx.matchedLength();
    }

    return 0;
}


#include <QString>
#include <QRegularExpression>
#include <QDebug>

int main() {
    QString str = "Hello, World! Hello, Qt!";

    // 使用 QRegularExpression 查找所有匹配的子字符串
    QRegularExpression re("Hello");
    QRegularExpressionMatchIterator it = re.globalMatch(str);
    while (it.hasNext()) {
        QRegularExpressionMatch match = it.next();
        qDebug() << "Found 'Hello' at index:" << match.capturedStart();
    }

    return 0;
}

10 检查字符串是否以特定子字符串开头

#include <QString>
#include <QDebug>

int main() {
    QString str = "Hello, World!";

    // 检查字符串是否以 "Hello" 开头
    bool startsWithHello = str.startsWith("Hello");
    qDebug() << "Starts with 'Hello':" << startsWithHello;  // 输出: "Starts with 'Hello': true"

    // 检查字符串是否以 "hello" 开头(大小写敏感)
    bool startsWithHelloInsensitive = str.startsWith("hello", Qt::CaseInsensitive);
    qDebug() << "Starts with 'hello' (case insensitive):" << startsWithHelloInsensitive;  // 输出: "Starts with 'hello' (case insensitive): true"

    return 0;
}

11.比较字符串

使用 operator== 和 operator!=

#include <QString>
#include <QDebug>

int main() {
    QString str1 = "Hello";
    QString str2 = "Hello";
    QString str3 = "World";

    // 比较字符串是否相等
    bool isEqual = (str1 == str2);
    qDebug() << "str1 == str2:" << isEqual;  // 输出: "str1 == str2: true"

    // 比较字符串是否不相等
    bool isNotEqual = (str1 != str3);
    qDebug() << "str1 != str3:" << isNotEqual;  // 输出: "str1 != str3: true"

    return 0;
}

使用 compare 方法

#include <QString>
#include <QDebug>

int main() {
    QString str1 = "Hello";
    QString str2 = "hello";

    // 比较字符串(大小写敏感)
    int result = str1.compare(str2);
    qDebug() << "str1.compare(str2):" << result;  // 输出: "str1.compare(str2): -32"

    // 比较字符串(大小写不敏感)
    int resultInsensitive = str1.compare(str2, Qt::CaseInsensitive);
    qDebug() << "str1.compare(str2, Qt::CaseInsensitive):" << resultInsensitive;  // 输出: "str1.compare(str2, Qt::CaseInsensitive): 0"

    return 0;
}

使用 localeAwareCompare 方法

localeAwareCompare 方法用于根据当前区域设置进行字符串比较。这对于需要考虑语言和文化差异的比较非常有用。

#include <QString>
#include <QDebug>

int main() {
    QString str1 = "Ångström";
    QString str2 = "Angstrom";

    // 使用区域设置进行比较
    int result = str1.localeAwareCompare(str2);
    qDebug() << "str1.localeAwareCompare(str2):" << result;  // 输出: "str1.localeAwareCompare(str2): -1"

    return 0;
}

使用 operator<, operator<=, operator>, operator>=

QString 还重载了 <, <=, >, >= 运算符,用于比较字符串的大小。

#include <QString>
#include <QDebug>

int main() {
    QString str1 = "apple";
    QString str2 = "banana";

    // 比较字符串大小
    bool isLess = (str1 < str2);
    qDebug() << "str1 < str2:" << isLess;  // 输出: "str1 < str2: true"

    bool isGreaterEqual = (str2 >= str1);
    qDebug() << "str2 >= str1:" << isGreaterEqual;  // 输出: "str2 >= str1: true"

    return 0;
}

字符串排序

#include <QStringList>
#include <QDebug>

int main() {
    QStringList list = {"banana", "apple", "cherry"};

    // 对字符串列表进行排序
    list.sort();
    qDebug() << "Sorted list:" << list;  // 输出: "Sorted list: ("apple", "banana", "cherry")"

    return 0;
}

12 使用 left, right, mid 方法提取子字符串

#include <QString>
#include <QDebug>

int main() {
    QString str = "Hello, World!";

    // 提取前5个字符
    QString leftStr = str.left(5);
    qDebug() << "Left 5 characters:" << leftStr;  // 输出: "Left 5 characters: Hello"

    // 提取后6个字符
    QString rightStr = str.right(6);
    qDebug() << "Right 6 characters:" << rightStr;  // 输出: "Right 6 characters: World!"

    // 提取从位置7开始的5个字符
    QString midStr = str.mid(7, 5);
    qDebug() << "Mid 5 characters from index 7:" << midStr;  // 输出: "Mid 5 characters from index 7: World"

    return 0;
}

13 使用 trimmed, simplified 方法清理字符串

trimmed 方法用于去除字符串两端的空白字符,而 simplified 方法不仅去除两端的空白字符,还用单个空格替换连续的空白字符。

#include <QString>
#include <QDebug>

int main() {
    QString str = "   Hello,   World!   ";

    // 去除两端的空白字符
    QString trimmedStr = str.trimmed();
    qDebug() << "Trimmed string:" << trimmedStr;  // 输出: "Trimmed string: Hello,   World!"

    // 去除两端的空白字符,并用单个空格替换连续的空白字符
    QString simplifiedStr = str.simplified();
    qDebug() << "Simplified string:" << simplifiedStr;  // 输出: "Simplified string: Hello, World!"

    return 0;
}

14.使用 toUpper, toLower 方法转换大小写

#include <QString>
#include <QDebug>

int main() {
    QString str = "Hello, World!";

    // 转换为大写
    QString upperStr = str.toUpper();
    qDebug() << "Uppercase string:" << upperStr;  // 输出: "Uppercase string: HELLO, WORLD!"

    // 转换为小写
    QString lowerStr = str.toLower();
    qDebug() << "Lowercase string:" << lowerStr;  // 输出: "Lowercase string: hello, world!"

    return 0;
}

15.使用 isNull 和 isEmpty 方法检查字符串状态

#include <QString>
#include <QDebug>

int main() {
    QString nullStr;
    QString emptyStr = "";
    QString nonEmptyStr = "Hello";

    // 检查字符串是否为空(未初始化)
    qDebug() << "Null string:" << nullStr.isNull();  // 输出: "Null string: true"
    qDebug() << "Empty string:" << emptyStr.isNull();  // 输出: "Empty string: false"

    // 检查字符串是否为空字符串(长度为0)
    qDebug() << "Empty string:" << emptyStr.isEmpty();  // 输出: "Empty string: true"
    qDebug() << "Non-empty string:" << nonEmptyStr.isEmpty();  // 输出: "Non-empty string: false"

    return 0;
}

16 将字符转换为 ASCII 码

#include <QString>
#include <QDebug>

int main() {
    QChar ch = 'A';

    // 获取字符的 ASCII 码
    ushort asciiCode = ch.unicode();
    qDebug() << "ASCII code of 'A':" << asciiCode;  // 输出: "ASCII code of 'A': 65"

    return 0;
}

17 将字符串转换为 UTF-8 编码

#include <QString>
#include <QDebug>
#include <QByteArray>

int main() {
    QString str = "你好,世界!";

    // 将字符串转换为 UTF-8 编码的字节数组
    QByteArray utf8Bytes = str.toUtf8();
    qDebug() << "UTF-8 bytes of '你好,世界!':" << utf8Bytes;  // 输出: "UTF-8 bytes of '你好,世界!': "\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81""

    return 0;
}

18.将 UTF-8 编码的字节数组转换为字符串

#include <QString>
#include <QDebug>
#include <QByteArray>

int main() {
    QByteArray utf8Bytes = QByteArray("\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81");

    // 将 UTF-8 编码的字节数组转换为字符串
    QString str = QString::fromUtf8(utf8Bytes);
    qDebug() << "String from UTF-8 bytes:" << str;  // 输出: "String from UTF-8 bytes: 你好,世界!"

    return 0;
}

19 使用 QTextCodec 进行编码转换

QTextCodec 类提供了更通用的方法来进行字符编码转换。以下是一个示例,展示如何使用 QTextCodec 将字符串转换为 UTF-8 编码并转换回字符串。

#include <QString>
#include <QDebug>
#include <QByteArray>
#include <QTextCodec>

int main() {
    QString str = "你好,世界!";

    // 获取 UTF-8 编码器
    QTextCodec *utf8Codec = QTextCodec::codecForName("UTF-8");

    // 将字符串转换为 UTF-8 编码的字节数组
    QByteArray utf8Bytes = utf8Codec->fromUnicode(str);
    qDebug() << "UTF-8 bytes of '你好,世界!':" << utf8Bytes;  // 输出: "UTF-8 bytes of '你好,世界!': "\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81""

    // 将 UTF-8 编码的字节数组转换为字符串
    QString restoredStr = utf8Codec->toUnicode(utf8Bytes);
    qDebug() << "String from UTF-8 bytes:" << restoredStr;  // 输出: "String from UTF-8 bytes: 你好,世界!"

    return 0;
}

20 使用 QTextStream 进行文件读写

在处理文件时,可以使用 QTextStream 并指定编码为 UTF-8,以便正确读写 UTF-8 编码的文本文件。

#include <QString>
#include <QDebug>
#include <QFile>
#include <QTextStream>

int main() {
    QString str = "你好,世界!";

    // 写入文件
    QFile file("output.txt");
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);
        out.setCodec("UTF-8");
        out << str;
        file.close();
    }

    // 读取文件
    QString fileContent;
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        in.setCodec("UTF-8");
        fileContent = in.readAll();
        file.close();
    }

    qDebug() << "File content:" << fileContent;  // 输出: "File content: 你好,世界!"

    return 0;
}

  • 12
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
QT字符串转换为时间戳涉及到将一个表示日期和时间的文本字符串转换成Unix时间戳值,这是一个自1970年1月1日以来所经历的秒数。这通常需要了解字符串中日期和时间的具体格式,并使用合适的函数进行解析。 ### 步骤: 1. **识别格式**:首先确定日期时间字符串的格式。例如,“YYYY-MM-DD HH:mm:ss”、“MM/DD/YYYY HH:MM:SS”等。不同的应用和系统可能会有不同的日期格式。 2. **选择适当的时间库**:在QT中处理日期和时间,可以利用`QDateTime`以及其相关的函数来进行。如果你是在QT C++环境中工作,那么`QDateTime`将会是一个关键的工具。 3. **创建QDateTime实例**:使用 `QDateTime::fromString()` 函数将字符串转换为 `QDateTime` 对象。此函数接受两个参数:你要解析的字符串和使用的日期时间格式。 4. **获取时间戳**:从 `QDateTime` 实例中获取时间戳。你可以通过调用 `toSecsSinceEpoch()` 函数得到时间戳。这个函数返回一个long整数,代表了从1970年1月1日起至今的总秒数。 下面是一个简单的示例代码段展示如何完成这一过程: ```cpp #include <QDateTime> #include <QString> int main() { QString dateString = "2023-05-16 14:30:00"; QLocale locale; // 使用当前系统的locale设置日期格式 // 尝试使用默认的日期格式,如果格式化失败会抛出异常 QDateTime dateTime = dateString.toDateTime(); if (dateTime.isValid()) { long timestamp = dateTime.toSecsSinceEpoch(); qDebug() << "Timestamp is:" << timestamp; } else { qDebug() << "Failed to parse date."; } return 0; } ``` ### 相关问题: 1. 如何在QT中验证日期时间字符串的有效性? - 可以使用 `QDateTime::fromString()` 的返回值来判断是否有效。如果是有效的,则 `QDateTime` 实例会被成功初始化;如果不是,则返回的实例将是无效的。 2. QT中有无其他方法直接计算时间戳而不使用 `QDateTime` ? - 如果只是简单的需求,而不需要使用到`QDateTime`的高级功能,可以直接使用Qt框架之外的标准C++库里的`std::chrono`和`std::istringstream`进行日期和时间的读取和转换,然后使用标准库的时间点或持续时间型如`std::chrono::time_point`和`std::chrono::duration`来处理。 3. 时间戳的精度是多少? - Unix时间戳的精度取决于底层操作系统的时间服务。通常情况下,一个Unix时间戳的精度大约是每秒,这意味着它可以提供毫秒级别的分辨率,但在某些场景下可能支持更高的精度。然而,注意由于溢出的问题,时间戳的上限约为2^31-1秒(约到2038年末),之后的时间表示就会出现问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可能只会写BUG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值