Question

For some reason I need to use string with fixed size. Now I'm looking on a QString class.
But there I have some questions with making QString object having constant size.
For example, I want to have string with size 10, it means, that if I would try to write some
string with more than 100 chars in it, it would cut all the characters after 100 one.
I found constructor for QString in Qt docs, but I'm not sure if it would work as I told

  • QString( int size , QChar ch)

What can you suggest in such situation?

Was it helpful?

Solution

You can have a wrapper class that has a string, but is not a string, yet it can be used wherever a QString could be used. It can also be used with all QString's methods and operators, as long as you treat it like it were a pointer.

#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");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top