📄 qstring.cpp
字号:
/******************************************************************************** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.**** This file is part of the QtCore module of the Qt Toolkit.**** This file may be used under the terms of the GNU General Public** License version 2.0 as published by the Free Software Foundation** and appearing in the file LICENSE.GPL included in the packaging of** this file. Please review the following information to ensure GNU** General Public Licensing requirements will be met:** http://trolltech.com/products/qt/licenses/licensing/opensource/**** If you are unsure which license is appropriate for your use, please** review the following information:** http://trolltech.com/products/qt/licenses/licensing/licensingoverview** or contact the sales department at sales@trolltech.com.**** In addition, as a special exception, Trolltech gives you certain** additional rights. These rights are described in the Trolltech GPL** Exception version 1.0, which can be found at** http://www.trolltech.com/products/qt/gplexception/ and in the file** GPL_EXCEPTION.txt in this package.**** In addition, as a special exception, Trolltech, as the sole copyright** holder for Qt Designer, grants users of the Qt/Eclipse Integration** plug-in the right for the Qt/Eclipse Integration to link to** functionality provided by Qt Designer and its related libraries.**** Trolltech reserves all rights not expressly granted herein.**** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.******************************************************************************/#include "qstringlist.h"#include "qregexp.h"#include "qunicodetables_p.h"#ifndef QT_NO_TEXTCODEC#include <qtextcodec.h>#endif#include <qdatastream.h>#include <qlist.h>#include "qlocale.h"#include "qlocale_p.h"#include "qstringmatcher.h"#include "qtools_p.h"#include "qhash.h"#include "qdebug.h"#ifdef Q_OS_MAC#include <private/qcore_mac_p.h>#endif#include <limits.h>#include <string.h>#include <stdlib.h>#include <stdio.h>#include <stdarg.h>#ifdef truncate#undef truncate#endif#include "qchar.cpp"#include "qstringmatcher.cpp"#ifndef LLONG_MAX#define LLONG_MAX qint64_C(9223372036854775807)#endif#ifndef LLONG_MIN#define LLONG_MIN (-LLONG_MAX - qint64_C(1))#endif#ifndef ULLONG_MAX#define ULLONG_MAX quint64_C(18446744073709551615)#endif#ifndef QT_NO_TEXTCODECQTextCodec *QString::codecForCStrings;#endif#ifdef QT3_SUPPORTstatic QHash<void *, QByteArray> *asciiCache = 0;#endifstatic int ucstricmp(const ushort *a, const ushort *ae, const ushort *b, const ushort *be){ if (a == b) return 0; if (a == 0) return 1; if (b == 0) return -1; const ushort *e = ae; if (be - b < ae - a) e = a + (be - b); uint alast = 0; uint blast = 0; while (a != e) {// qDebug() << hex << alast << blast;// qDebug() << hex << "*a=" << *a << "alast=" << alast << "folded=" << foldCase (*a, alast);// qDebug() << hex << "*b=" << *b << "blast=" << blast << "folded=" << foldCase (*b, blast); int diff = foldCase(*a, alast) - foldCase(*b, blast); if ((diff)) return diff; ++a; ++b; } if (a == ae) { if (b == be) return 0; return -1; } return 1;}static int ucstricmp(const ushort *a, const ushort *ae, const uchar *b){ if (a == 0) { if (b == 0) return 0; return 1; } if (b == 0) return -1; while (a != ae && *b) { int diff = foldCase(*a) - foldCase(*b); if ((diff)) return diff; ++a; ++b; } if (a == ae) { if (!*b) return 0; return -1; } return 1;}static int ucstrcmp(const QChar *a, int alen, const QChar *b, int blen){ if (a == b) return 0; int l = qMin(alen, blen); while (l-- && *a == *b) a++,b++; if (l == -1) return (alen-blen); return a->unicode() - b->unicode();}inline int ucstrcmp(const QString &as, const QString &bs){ return ucstrcmp(as.unicode(), as.size(), bs.unicode(), bs.size());}inline int ucstrcmp(const QStringRef &as, const QStringRef &bs){ return ucstrcmp(as.unicode(), as.size(), bs.unicode(), bs.size());}static int ucstrncmp(const QChar *a, const QChar *b, int l){ while (l-- && *a == *b) a++,b++; if (l==-1) return 0; return a->unicode() - b->unicode();}static int ucstrnicmp(const ushort *a, const ushort *b, int l){ return ucstricmp(a, a + l, b, b + l);}inline bool qIsUpper(char ch){ return ch >= 'A' && ch <= 'Z';}inline bool qIsDigit(char ch){ return ch >= '0' && ch <= '9';}inline char qToLower(char ch){ if (ch >= 'A' && ch <= 'Z') return ch - 'A' + 'a'; else return ch;}const QString::Null QString::null = QString::Null();/*! \macro QT_NO_CAST_FROM_ASCII \relates QString Disables automatic conversions from 8-bit strings (char *) to unicode QStrings \sa QT_NO_CAST_TO_ASCII*//*! \macro QT_NO_CAST_TO_ASCII \relates QString disables automatic conversion from QString to ASCII 8-bit strings (char *) \sa QT_NO_CAST_FROM_ASCII*//*! \macro QT_ASCII_CAST_WARNINGS \internal \relates QString This macro can be defined to force a warning whenever a function is called that automatically converts between unicode and 8-bit encodings. Note: This only works for compilers that support warnings for deprecated API. \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII*//*! \class QCharRef \reentrant \brief The QCharRef class is a helper class for QString. \internal \ingroup text When you get an object of type QCharRef, if you can assign to it, the assignment will apply to the character in the string from which you got the reference. That is its whole purpose in life. The QCharRef becomes invalid once modifications are made to the string: if you want to keep the character, copy it into a QChar. Most of the QChar member functions also exist in QCharRef. However, they are not explicitly documented here. \sa QString::operator[]() QString::at() QChar*//*! \class QString \reentrant \brief The QString class provides a Unicode character string. \ingroup tools \ingroup shared \ingroup text \mainclass \reentrant QString stores a string of 16-bit \l{QChar}s, where each QChar corresponds one Unicode 4.0 character. (Unicode characters with code values above 65535 are stored using surrogate pairs, i.e., two consecutive \l{QChar}s.) \l{Unicode} is an international standard that supports most of the writing systems in use today. It is a superset of ASCII and Latin-1 (ISO 8859-1), and all the ASCII/Latin-1 characters are available at the same code positions. Behind the scenes, QString uses \l{implicit sharing} (copy-on-write) to reduce memory usage and to avoid the needless copying of data. This also helps reduce the inherent overhead of storing 16-bit characters instead of 8-bit characters. In addition to QString, Qt also provides the QByteArray class to store raw bytes and traditional 8-bit '\\0'-terminated strings. For most purposes, QString is the class you want to use. It is used throughout the Qt API, and the Unicode support ensures that your applications will be easy to translate if you want to expand your application's market at some point. The two main cases where QByteArray is appropriate are when you need to store raw binary data, and when memory conservation is critical (e.g. with \l { Qtopia Core}). \tableofcontents \section1 Initializing a String One way to initialize a QString is simply to pass a \c{const char *} to its constructor. For example, the following code creates a QString of size 5 containing the data "Hello": \quotefromfile snippets/qstring/main.cpp \skipto Widget::constCharPointer() \skipto Hello \printline Hello QString converts the \c{const char *} data into Unicode using the fromAscii() function. By default, fromAscii() treats character above 128 as Latin-1 characters, but this can be changed by calling QTextCodec::setCodecForCStrings(). In all of the QString functions that take \c{const char *} parameters, the \c{const char *} is interpreted as a classic C-style '\\0'-terminated string. It is legal for the \c{const char *} parameter to be 0. You can also provide string data as an array of \l{QChar}s: \skipto Widget::constCharArray() \skipto static const \printuntil str 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.) Another approach is to set the size of the string using resize() and to initialize the data character per character. QString uses 0-based indexes, just like C++ arrays. To access the character at a particular index position, you can use \l operator[](). On non-const strings, \l operator[]() returns a reference to a character that can be used on the left side of an assignment. For example: \skipto Widget::characterReference() \skipto QString str \printuntil str[3] = QChar(0x03a3) For read-only access, an alternative syntax is to use the at() function: \skipto Widget::atFunction() \skipto QString str \printuntil } The at() function can be faster than \l operator[](), because it never causes a \l{deep copy} to occur. Alternatively, use the left(), right(), or mid() functions to extract several characters at a time. A QString can embed '\\0' characters (QChar::null). The size() function always returns the size of the whole string, including embedded '\\0' characters. 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. QString provides dozens of overloads designed to simplify string usage. For example, if you want to compare a QString with a string literal, you can write code like this and it will work as expected: \skipto Widget::stringLiteral() \skipto QString str \printuntil } 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 \c{const char *} argument using the \l qPrintable() macro which returns the given QString as a \c{const char *}. This is equivalent to calling <QString>.toAscii().constData(). \section1 Manipulating String Data QString provides the following basic functions for modifying the character data: append(), prepend(), insert(), replace(), and remove(). For example: \skipto Widget::modify() \skipto QString str \printuntil str.replace(5, 3, "&") 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 QString actually allocated. The replace() and remove() functions' first two arguments are the position from which to start erasing and the number of characters that should be erased. If you want to replace all occurrences of a particular substring with another, use one of the two-parameter replace() overloads. A frequent requirement is to remove whitespace characters from a string ('\\n', '\\t', ' ', etc.). If you want to remove whitespace from both ends of a QString, use the trimmed() function. If you want to remove whitespace from both ends and replace multiple consecutive whitespaces with a single space character within the string, use 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. For example, here's a typical loop that finds all occurrences of a particular substring: \skipto Widget::index() \skipto QString str \printuntil } 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 that match a particular QRegExp using the QStringList::find() function.: \section1 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(). QStrings can be compared using overloaded operators such as \l operator<(), \l operator<=(), \l operator==(), \l operator>=(), and so on. Note that the comparison is based exclusively on the
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -