当前位置: 首页 > news >正文

QT6 源(62)篇五:阅读与注释 QString 这个类,先给出官方综述,带一些翻译。总篇目太大,代码就有 2000 行

(8)

/* Detailed Description 这些翻译来自官方讲解
QString 存储 16 位 QChars 的字符串,其中每个 QChar 对应一个 UTF-16 代码单元。
代码值大于 65535 的 Unicode 字符使用助记符对存储,即两个连续的 QChars。)Unicode 是一种国际标准,支持当今使用的多数书写系统。
它是 US-ASCII(ANSIX3.4-1986)和Latin-1(IS0 8859-1)的超集,
所有 US-ASCIl/Latin-1 字符都在相同的代码位置可用。在幕后,QString使用隐式共享(写时复制)来减少内存使用并避免不必要的数据复制。
这也有助于减少存储 16 位字符而不是 8位字符的固有开销。除了QString,Qt还提供了QByteArray类来存储原始字节和传统8位'0'终止的字符串。
对于大多数用途,QString是您想要使用的类。它在整个Qt API中使用,
Unicode支持确保您的应用程序在需要扩展应用程序市场时易于翻译。
QBvteArray适合使用的主要情况是当您需要存储原始二进制数据时,
以及当内存保护至关重要时(如在嵌入式系统中).Initializing a String++++++++++++++++++++One way to initialize a QString is simply to pass a const char * to its constructor.
For example, the following code creates a QString of size 5 containing the
data "Hello":    QString str = "Hello";In all of the QString functions that take const char * parameters,
the const char * is interpreted as a classic C-style '\0'-terminated string
encoded in UTF-8. It is legal for the const char * parameter to be nullptr.QString makes a deep copy of the QChar data,
so you can modify it later without experiencing side effects.
(If for performance reasons you don't want to take a deep copy of the character data,
use QString::fromRawData() instead.)另一种方法是使用resize()设置字符串的大小,并逐字符初始化数据字符。
QString使用基于0的索引,就像C++数组一样。
要访问特定索引位置的字符,可以使用  operator[]()。
对于非常量字符串, operator[]()返回一个字符的引用,该引用可以在赋值左侧使用。For read-only access, an alternative syntax is to use the at() function。The at() function can be faster than operator[](),
because it never causes a deep copy to occur.
Alternatively, use the first(), last(), or sliced() functions to
extract several characters at a time.-个QString可以嵌入"0'字符(QChar::Nul)。size()函数总是返回整个字符串的大小,包括嵌入的"0'字符。
A QString can embed '\0' characters (QChar::Null).
The size() function always returns the size of the whole string,
including embedded '\0' characters.       ---->包括'\0' 这跟以往有很大不同。After a call to the resize() function,
newly allocated characters have undefined values.
To set all the characters in the string to a particular value,
use the fill() function.You can also pass string literals to functions that take QStrings as arguments,
invoking the QString(const char *) constructor.
Similarly, you can pass a QString to a function that takes a
const char * argument using the qPrintable() macro which returns the
given QString as a const char *.  ---->意思是 QString 会被隐式的转换为 c 字符串来使用。
This is equivalent to calling <QString>.toLocal8Bit().constData().Manipulating String Data++++++++++++++++++++QString provides the following basic functions for modifying the character data:
append(), prepend(), insert(), replace(), and remove().In the above example the replace() function's first two arguments are the
position from which to start replacing and the number of characters that should
be replaced.When data-modifying functions increase the size of the string,
they may lead to reallocation of memory for the QString object.
When this happens, QString expands by more than it immediately needs so as to
have space for further expansion without reallocation until the size of the
string has greatly increased.The insert(), remove() and, when replacing a sub-string with one of different size,
replace() functions can be slow (linear time) for large strings,
because they require moving many characters in the string by at least one
position in memory.If you are building a QString gradually and know in advance approximately how
many characters the QString will contain, you can call reserve(),
asking QString to preallocate a certain amount of memory.
You can also call capacity() to find out how much memory the QString actually
has allocated.QString provides STL-style iterators (QString::const_iterator and QString::iterator).
In practice, iterators are handy when working with generic algorithms
provided by the C++ standard library.Note: Iterators over a QString, and references to individual characters within one,
cannot be relied on to remain valid when any non-const method of the QString is called.
Accessing such an iterator or reference after the call to a non-const method leads to
undefined behavior. When stability for iterator-like functionality is required,
you should use indexes instead of iterators as they are not tied to
QString's internal state and thus do not get invalidated.Note: Due to implicit sharing,
the first non-const operator or function used on a given QString may cause it to,
internally, perform a deep copy of its data.
This invalidates all iterators over the string and references to individual
characters within it. After the first non-const operator,
operations that modify QString may completely (in case of reallocation) or
partially invalidate iterators and references,
but other methods (such as begin() or end()) will not.
Accessing an iterator or reference after it has been invalidated leads to
undefined behavior.-个常见的要求是从字符串中删除空格字符('n'、"等)。
如果要从 QString的两端删除空格,请使用trimmed()函数。
如果要删除两端的空格,并将字符串中的多个连续空格替换为单个空格字符,请使用simplified()。If you want to find all occurrences of a particular character or
substring in a QString, use the indexOf() or lastIndexOf() functions.
The former searches forward starting from a given index position,
the latter searches backward.
Both return the index position of the character or substring if they find it;
otherwise, they return -1.QString provides many functions for converting numbers into strings and
strings into numbers. See the arg() functions, the setNum() functions,
the number() static functions, and the toInt(), toDouble(), and similar functions.To get an upper- or lowercase version of a string use toUpper() or toLower().Lists of strings are handled by the QStringList class.
You can split a string into a list of strings using the split() function,
and join a list of strings into a single string with an optional separator using
QStringList::join(). You can obtain a list of strings from a string list that contain
a particular substring or     //using QStringList = QList<QString>;这是 QList 的功能
that match a particular QRegularExpression using the QStringList::filter() function.Querying String Data++++++++++++++++++++If you want to see if a QString starts or ends with a particular substring use
startsWith() or endsWith(). If you simply want to check whether a
QString contains a particular character or substring, use the contains() function.
If you want to find out how many times a particular character or
substring occurs in the string, use count().To obtain a pointer to the actual character data, call data() or constData().
These functions return a pointer to the beginning of the QChar data.
The pointer is guaranteed to remain valid until
a non-const function is called on the QString.Comparing Strings++++++++++++++++++++QStrings can be compared using overloaded operators such as operator<(),
operator<=(), operator==(), operator>=(), and so on.
Note that the comparison is based exclusively on the numeric Unicode values of the
characters. It is very fast, but is not what a human would expect;
the QString::localeAwareCompare() function is usually a better choice for sorting
user-interface strings, when such a comparison is available.On Unix-like platforms (including Linux, macOS and iOS),
when Qt is linked with the ICU library (which it usually is),
its locale-aware sorting is used. Otherwise, on macOS and iOS,
localeAwareCompare() compares according the "Order for sorted lists" setting in the
International preferences panel. On other Unix-like systems without ICU,
the comparison falls back to the system library's strcoll(),Converting Between Encoded Strings Data and QString++++++++++++++++++QString provides the following three functions that return a const char * version of
the string as QByteArray: toUtf8(), toLatin1(), and toLocal8Bit().toLatin1   () returns a Latin-1 (ISO 8859-1) encoded 8-bit string.toUtf8     () returns a UTF-8 encoded 8-bit string.UTF-8 is a superset of US-ASCII (ANSI X3.4-1986) that supports the entireUnicode character set through multibyte sequences.toLocal8Bit() returns an 8-bit string using the system's local encoding.This is the same as toUtf8() on Unix systems.To convert from one of these encodings, QString provides fromLatin1(), fromUtf8(),
and fromLocal8Bit().
Other encodings are supported through the QStringEncoder and QStringDecoder classes.如上所述,QString提供了许多函数和运算符,可以轻松地与 const char*字符串进行互作。
但是这个功能是一把双刃剑:如果所有字符串都是 US-ASCIl或 Latin-1,
它使 QString 使用起来更方便但始终存在从或到 const char*的隐式转换使用错误的8位编码完成的风险。
为了最大限度地降低这些风险,您可以通过定义以下一些预处理器符号来关闭这些隐式转换:QT_NO_CAST_FROM_ASCII disables automatic conversions from C string literalsand pointers to Unicode.QT_RESTRICTED_CAST_FROM_ASCII allows automatic conversions from C charactersand character arrays,but disables automatic conversions from character pointers to Unicode.QT_NO_CAST_TO_ASCII disables automatic conversion from QString to C strings.You then need to explicitly call fromUtf8(), fromLatin1(), or fromLocal8Bit() to
construct a QString from an 8-bit string, or use the lightweight QLatin1String class,
for example:   QString url = QLatin1String("https://www.unicode.org/");Similarly, you must call toLatin1(), toUtf8(), or toLocal8Bit() explicitly
to convert the QString to an 8-bit string.Distinction Between Null and Empty Strings++++++++++++++++++++++For historical reasons, QString distinguishes between a null string and an
empty string. A null string is a string that is initialized using QString's default
constructor or by passing (const char *)0 to the constructor.
An empty string is any string with size 0. A null string is always empty,but an empty string isn't necessarily null:All functions except isNull() treat null strings the same as empty strings.
For example, toUtf8().constData() returns a valid pointer (not nullptr) to
a '\0' character for a null string.   //尽量多用 isEmpty() 这个成员函数
We recommend that you always use the isEmpty() function and avoid isNull().Number Formats++++++++++++++++++当QString:arg()'%"格式说明符包含"!'本地域限定符,且基数为十(其默认值)时,将使用默认本地域。
这可以通过QLocale:setDefault()设置。
对于更精细地控制本地化数字的表示形式,请参见QLocale::toString()。
由QString执行的所有其他数字格式化遵循C本地域的数字表示形式。
当QString::arg()对数字应用左填充时,填充字符0'会被特殊处理。
如果数字为负数,则其减号将出现在零填充之前。
如果字段已本地化,则使用适合区域设置的零字符代替'0'。对于浮点数,此特殊处理仅在数字有限时适用。Floating-point Formats+++++++++++++++++++++In member functions (e.g., arg(), number()) that represent floating-point numbers
(float or double) as strings, the form of display can be controlled by a choice of
format and precision, whose meanings are as for QLocale::toString(double, char, int).
If the selected format includes an exponent, localized forms follow the locale's
convention on digits in the exponent. For non-localized formatting,
the exponent shows its sign and includes at least two digits,
left-padding with zero if needed.More Efficient String Construction+++++++++++++++++++++++++++++许多字符串在编译时已知。
但是,微不足道的构造函数QString("Hello"),将复制字符串的内容,将内容视为拉丁1。
为了避免这种情况,可以使用QStringLiteral宏在编译时直接创建所需的数据。
从字面量构造QString不会在运行时产生任何开销。A slightly less efficient way is to use QLatin1String.
This class wraps a C string literal,
precalculates it length at compile time and can then be used for faster
comparison with QStrings and conversion to QStrings than a regular C string literal.Using the QString '+' operator,
it is easy to construct a complex string from multiple substrings.Maximum Size and Out-of-memory Conditions+++++++++++++++++++++QString的最大大小取决于体系结构。大多数 64 位系统可以分配超过 2GB 的内存,通常限制为 2^63 字节。
实际值还取决于管理数据块所需的开销。因此,在32位平台上,最大大小为 2 GB 减去开销,
在 64 位平台上最大大小为 2^63 字节减去开销。
QString中可以存储的元素数量是这个最大大小除以 QChar 的大小。
当内存分配失败时,如果应用程序在编译时启用了异常支持,
则QString会抛出std:bad alloc异常在Qt容器中,内存不足是Qt抛出异常的唯一情况。
如果禁用了异常,则内存不足是未定义行为。
请注意,操作系统可能会对占用大量分配内存的应用程序施加进一步的限制,特别是大且连续的块。
此类考虑、此类行为的配置或任何缓解措施超出了OtAPI的范围。*/

(9)

谢谢

相关文章:

  • 机器学习,深度学习
  • 全面接入!Qwen3现已上线千帆
  • 第八节:目录操作
  • 晶振:从消费电子到航天领域的时间精度定义者
  • 第六部分:实战项目与拓展
  • VS Code技巧2:识别FreeCAD对象
  • 可视化图解算法:判断是否完全二叉树
  • 基于SpringBoot的母婴商城系统设计与实现(附源码+PPT+论文)
  • 【操作系统】进程和线程的区别
  • /var/log/sssd/` 目录解析
  • HTN77A0原理图提供聚能芯半导体禾润一级代理技术支持免费送样
  • MySQL学习笔记(基础篇)
  • 解锁Windows异步黑科技:IOCP从入门到精通
  • 虚拟机安装SQLServer2000
  • 用Ai学习wxWidgets笔记——自制wxWidgets开发参考手册(主体)
  • 在油气地震资料积分法偏移成像中,起伏地表处理
  • agent course-2
  • CBC(Clock Boundary Crossing)简介
  • SVTAV1 编码函数 svt_aom_is_pic_skipped
  • Linux -- 操作系统
  • 解放日报:让算力像“水电煤”赋能千行百业
  • 擦亮“世界美食之都”金字招牌,淮安的努力不止于餐桌
  • 澎湃回声丨23岁小伙“被精神病”8年续:今日将被移出“重精”管理系统
  • 中央宣传部、全国总工会联合发布2025年“最美职工”先进事迹
  • 78家公募年度业绩比拼:23家营收净利双升,十强座次微调
  • 五一假期上海推出首批16条“市民健康路线”,这些健康提示请收好