c++ - 固定 QString 大小(长度)

标签 c++ string qt qstring

出于某种原因,我需要使用固定大小的字符串。现在我在看 QString 类。
但是我对使 QString 对象具有恒定大小有一些疑问。
例如,我想要一个大小为 10 的字符串,这意味着,如果我尝试编写一些
其中包含超过 100 个字符的字符串,它将删除 100 个之后的所有字符。
我在 Qt 文档中找到了 QString 的构造函数,但我不确定它是否会像我说的那样工作

  • QString( int size , QChar ch)

在这种情况下你有什么建议?

最佳答案

你可以有一个包装器类,它有一个字符串,但不是字符串,但它可以用在任何QString可以用的地方使用。它也可以与所有 QString 的方法和运算符一起使用,只要您将其视为指针即可。

#include <QString>

class FixedWidthString {
  mutable QString m_string;
  //! Ignored if negative.
  int m_maxLength;
  inline const QString& data() const {
      if (m_maxLength >= 0 && m_string.length() > m_maxLength)
          m_string.truncate(m_maxLength);
      return m_string;
  }
  inline QString& data() {
      if (m_maxLength >= 0 && m_string.length() > m_maxLength)
          m_string.truncate(m_maxLength);
      return m_string;
  }
public:
  explicit FixedWidthString(int maxLength = -1) : m_maxLength(maxLength) {}
  explicit FixedWidthString(const QString & str, int maxLength = -1) : m_string(str), m_maxLength(maxLength) {}
  operator const QString&() const { return data(); }
  operator QString&() { return data(); }
  QString* operator->() { return &data(); }
  const QString* operator->() const { return &data(); }
  QString& operator*() { return data(); }
  const QString& operator*() const { return data(); }
  FixedWidthString & operator=(const FixedWidthString& other) {
      m_string = *other;
      return *this;
  }
};

int main() {
    FixedWidthString fs(3);
    FixedWidthString fs2(2);
    *fs = "FooBarBaz";
    Q_ASSERT(*fs == "Foo");
    fs->truncate(2);
    Q_ASSERT(*fs == "Fo");
    fs->append("Roo");
    Q_ASSERT(*fs == "FoR");
    fs->truncate(1);
    *fs += "abc";
    Q_ASSERT(*fs == "Fab");
    fs2 = fs;
    Q_ASSERT(*fs2 == "Fa");
}

关于c++ - 固定 QString 大小(长度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21334850/

相关文章:

c++ - 如何使用 LLVM 4.1 忽略 Xcode 中的外联定义错误

c++ - 我的 C++ 代码在尝试计算表中元素的总和时崩溃

c++ - 如何使用 Zstd 压缩 C++ 字符串?

python - 为什么 itemAt() 并不总能找到 QGraphicsItem

c++ - 在 Release模式下调用 delete 时未删除 fstreams

c++ - 深度复制链表 - O(n)

c++ - fgets() 不会在空字符串上返回 NULL

c# - 从 C# 中的字符串中删除换行符的最快方法是什么?

c++ - 仅在填充两个字段时启用按钮

c++ - 我们可以在构造函数中定义静态类成员吗?