1
/****************************************************************************
3
** Copyright (C) 1992-2005 Trolltech AS. All rights reserved.
5
** This file is part of the Qt 3 compatibility classes of the Qt Toolkit.
7
** This file may be distributed under the terms of the Q Public License
8
** as defined by Trolltech AS of Norway and appearing in the file
9
** LICENSE.QPL included in the packaging of this file.
11
** This file may be distributed and/or modified under the terms of the
12
** GNU General Public License version 2 as published by the Free Software
13
** Foundation and appearing in the file LICENSE.GPL included in the
14
** packaging of this file.
16
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
17
** information about Qt Commercial License Agreements.
18
** See http://www.trolltech.com/qpl/ for QPL licensing information.
19
** See http://www.trolltech.com/gpl/ for GPL licensing information.
21
** Contact info@trolltech.com if any conditions of this licensing are
24
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
25
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27
****************************************************************************/
29
#include "q3cstring.h"
31
#include "qdatastream.h"
40
/*****************************************************************************
41
Q3CString member functions
42
*****************************************************************************/
45
\class Q3CString q3cstring.h
47
\brief The Q3CString class provides an abstraction of the classic C
48
zero-terminated char array (char *).
52
Q3CString tries to behave like a more convenient \c{const char *}.
53
The price of doing this is that some algorithms will perform
54
badly. For example, append() is O(length()) since it scans for a
55
null terminator. Although you might use Q3CString for text that is
56
never exposed to the user, for most purposes, and especially for
57
user-visible text, you should use QString. QString provides
58
implicit sharing, Unicode and other internationalization support,
59
and is well optimized.
61
Note that for the Q3CString methods that take a \c{const char *}
62
parameter the \c{const char *} must either be 0 (null) or not-null
63
and '\0' (NUL byte) terminated; otherwise the results are
66
A Q3CString that has not been assigned to anything is \e null, i.e.
67
both the length and the data pointer is 0. A Q3CString that
68
references the empty string ("", a single '\0' char) is \e empty.
69
Both null and empty Q3CStrings are legal parameters to the methods.
70
Assigning \c{const char *} 0 to Q3CString produces a null Q3CString.
72
The length() function returns the length of the string; resize()
73
resizes the string and truncate() truncates the string. A string
74
can be filled with a character using fill(). Strings can be left
75
or right padded with characters using leftJustify() and
76
rightJustify(). Characters, strings and regular expressions can be
77
searched for using find() and findRev(), and counted using
80
Strings and characters can be inserted with insert() and appended
81
with append(). A string can be prepended with prepend().
82
Characters can be removed from the string with remove() and
83
replaced with replace().
85
Portions of a string can be extracted using left(), right() and
86
mid(). Whitespace can be removed using stripWhiteSpace() and
87
simplifyWhiteSpace(). Strings can be converted to uppercase or
88
lowercase with upper() and lower() respectively.
90
Strings that contain numbers can be converted to numbers with
91
toShort(), toInt(), toLong(), toULong(), toFloat() and toDouble().
92
Numbers can be converted to strings with setNum().
94
Many operators are overloaded to work with Q3CStrings. Q3CString
95
also supports some more obscure functions, e.g. sprintf(),
96
setStr() and setExpand().
98
\sidebar Note on Character Comparisons
100
In Q3CString the notion of uppercase and lowercase and of which
101
character is greater than or less than another character is locale
102
dependent. This affects functions which support a case insensitive
103
option or which compare or lowercase or uppercase their arguments.
104
Case insensitive operations and comparisons will be accurate if
105
both strings contain only ASCII characters. (If \c $LC_CTYPE is
106
set, most Unix systems do "the right thing".) Functions that this
107
affects include contains(), find(), findRev(), \l operator<(), \l
108
operator<=(), \l operator>(), \l operator>=(), lower() and
111
This issue does not apply to \l{QString}s since they represent
112
characters using Unicode.
115
Performance note: The Q3CString methods for QRegExp searching are
116
implemented by converting the Q3CString to a QString and performing
117
the search on that. This implies a deep copy of the Q3CString data.
118
If you are going to perform many QRegExp searches on a large
119
Q3CString, you will get better performance by converting the
120
Q3CString to a QString yourself, and then searching in the QString.
124
\fn Q3CString Q3CString::left(uint len) const
130
\fn Q3CString Q3CString::right(uint len) const
136
\fn Q3CString Q3CString::mid(uint index, uint len) const
142
\fn Q3CString Q3CString::lower() const
144
Use QByteArray::toLower() instead.
148
\fn Q3CString Q3CString::upper() const
150
Use QByteArray::toUpper() instead.
154
\fn Q3CString Q3CString::stripWhiteSpace() const
156
Use QByteArray::trimmed() instead.
160
\fn Q3CString Q3CString::simplifyWhiteSpace() const
162
Use QByteArray::simplified() instead.
166
\fn Q3CString& Q3CString::insert(uint index, const char *c)
172
\fn Q3CString& Q3CString::insert(uint index, char c)
178
\fn Q3CString& Q3CString::prepend(const char *c)
184
\fn Q3CString& Q3CString::remove(uint index, uint len)
190
\fn Q3CString& Q3CString::replace(uint index, uint len, const char *c)
196
\fn Q3CString& Q3CString::replace(char c, const Q3CString &after)
202
\fn Q3CString& Q3CString::replace(char c, const char *after)
208
\fn Q3CString& Q3CString::replace(const Q3CString &b, const Q3CString &a)
214
\fn Q3CString& Q3CString::replace(const char *b, const char *a)
220
\fn Q3CString& Q3CString::replace(char b, char a)
226
\fn Q3CString::Q3CString()
228
Constructs a null string.
234
\fn Q3CString::Q3CString(const QByteArray &ba)
236
Constructs a copy of \a ba.
240
\fn Q3CString::Q3CString(const Q3CString &s)
242
Constructs a shallow copy \a s.
245
/*! \fn Q3CString::Q3CString(int size)
246
Constructs a string with room for \a size characters, including
247
the '\0'-terminator. Makes a null string if \a size == 0.
249
If \a size \> 0, then the first and last characters in the string
250
are initialized to '\0'. All other characters are uninitialized.
252
\sa resize(), isNull()
255
/*! \fn Q3CString::Q3CString(const char *str)
256
Constructs a string that is a deep copy of \a str.
258
If \a str is 0 a null string is created.
264
/*! \fn Q3CString::Q3CString(const char *str, uint maxsize)
266
Constructs a string that is a deep copy of \a str. The copy will
267
be at most \a maxsize bytes long including the '\0'-terminator.
271
Q3CString str("helloworld", 6); // assigns "hello" to str
274
If \a str contains a 0 byte within the first \a maxsize bytes, the
275
resulting Q3CString will be terminated by this 0. If \a str is 0 a
276
null string is created.
282
\fn Q3CString &Q3CString::operator=(const QByteArray &ba)
284
Assigns byte array \a ba to this Q3CString.
288
\fn Q3CString &Q3CString::operator=(const Q3CString &s)
290
Assigns a shallow copy of \a s to this string and returns a
291
reference to this string.
295
\fn Q3CString &Q3CString::operator=(const char *str)
298
Assigns a deep copy of \a str to this string and returns a
299
reference to this string.
301
If \a str is 0 a null string is created.
307
\fn bool Q3CString::isNull() const
309
Returns true if the string is null, i.e. if data() == 0; otherwise
310
returns false. A null string is also an empty string.
314
Q3CString a; // a.data() == 0, a.size() == 0, a.length() == 0
315
Q3CString b == ""; // b.data() == "", b.size() == 1, b.length() == 0
316
a.isNull(); // true because a.data() == 0
317
a.isEmpty(); // true because a.length() == 0
318
b.isNull(); // false because b.data() == ""
319
b.isEmpty(); // true because b.length() == 0
322
\sa isEmpty(), length(), size()
326
\fn bool Q3CString::isEmpty() const
328
Returns true if the string is empty, i.e. if length() == 0;
329
otherwise returns false. An empty string is not always a null
332
See example in isNull().
334
\sa isNull(), length(), size()
338
\fn uint Q3CString::length() const
340
Returns the length of the string, excluding the '\0'-terminator.
341
Equivalent to calling \c strlen(data()).
343
Null strings and empty strings have zero length.
345
\sa size(), isNull(), isEmpty()
349
\fn bool Q3CString::truncate(uint pos)
351
Truncates the string at position \a pos.
353
Equivalent to calling \c resize(pos+1).
357
Q3CString s = "truncate this string";
358
s.truncate(5); // s == "trunc"
367
Implemented as a call to the native vsprintf() (see the manual for
370
If the string is shorter than 256 characters, this sprintf() calls
371
resize(256) to decrease the chance of memory corruption. The
372
string is resized back to its actual length before sprintf()
378
s.sprintf("%d - %s", 1, "first"); // result < 256 chars
380
Q3CString big(25000); // very long string
381
big.sprintf("%d - %s", 2, longString); // result < 25000 chars
384
\warning All vsprintf() implementations will write past the end of
385
the target string (*this) if the \a format specification and
386
arguments happen to be longer than the target string, and some
387
will also fail if the target string is longer than some arbitrary
388
implementation limit.
390
Giving user-supplied arguments to sprintf() is risky: Sooner or
391
later someone will paste a huge line into your application.
394
Q3CString &Q3CString::sprintf(const char *format, ...)
398
va_start(ap, format);
400
resize(256); // make string big enough
401
vsprintf(data(), format, ap);
402
resize(qstrlen(constData()));
410
\fn Q3CString Q3CString::copy() const
412
Returns a deep copy of this string.
419
Returns a string of length \a width (plus one for the terminating
420
'\0') that contains this string padded with the \a fill character.
422
If the length of the string exceeds \a width and \a truncate is
423
false (the default), then the returned string is a copy of the
424
string. If the length of the string exceeds \a width and \a
425
truncate is true, then the returned string is a left(\a width).
429
Q3CString s("apple");
430
Q3CString t = s.leftJustify(8, '.'); // t == "apple..."
436
Q3CString Q3CString::leftJustify(uint width, char fill, bool truncate) const
439
int len = qstrlen(constData());
440
int padlen = width - len;
442
result.resize(len+padlen);
443
memcpy(result.data(), constData(), len);
444
memset(result.data()+len, fill, padlen);
447
result = left(width);
455
Returns a string of length \a width (plus one for the terminating
456
'\0') that contains zero or more of the \a fill character followed
459
If the length of the string exceeds \a width and \a truncate is
460
false (the default), then the returned string is a copy of the
461
string. If the length of the string exceeds \a width and \a
462
truncate is true, then the returned string is a left(\a width).
467
Q3CString t = s.rightJustify(8, '.'); // t == ".....pie"
473
Q3CString Q3CString::rightJustify(uint width, char fill, bool truncate) const
476
int len = qstrlen(constData());
477
int padlen = width - len;
479
result.resize(len+padlen);
480
memset(result.data(), fill, padlen);
481
memcpy(result.data()+padlen, constData(), len);
484
result = left(width);
492
Returns the string converted to a \c long value.
494
If \a ok is not 0: *\a ok is set to false if the string is not a
495
number, or if it has trailing garbage; otherwise *\a ok is set to
499
long Q3CString::toLong(bool *ok) const
501
const char *p = constData();
503
const long max_mult = 214748364;
508
while (isspace((uchar) *p)) // skip leading space
513
} else if (*p == '+') {
516
if (!isdigit((uchar) *p))
518
while (isdigit((uchar) *p)) {
519
if (val > max_mult || (val == max_mult && (*p-'0') > 7+neg))
521
val = 10*val + (*p++ - '0');
525
while (isspace((uchar) *p)) // skip trailing space
532
return is_ok ? val : 0;
536
Returns the string converted to an \c{unsigned long} value.
538
If \a ok is not 0: *\a ok is set to false if the string is not a
539
number, or if it has trailing garbage; otherwise *\a ok is set to
543
ulong Q3CString::toULong(bool *ok) const
545
const char *p = constData();
547
const ulong max_mult = 429496729;
551
while (isspace((uchar) *p)) // skip leading space
555
if (!isdigit((uchar) *p))
557
while (isdigit((uchar) *p)) {
558
if (val > max_mult || (val == max_mult && (*p-'0') > 5))
560
val = 10*val + (*p++ - '0');
562
while (isspace((uchar) *p)) // skip trailing space
569
return is_ok ? val : 0;
573
Returns the string converted to a \c{short} value.
575
If \a ok is not 0: *\a ok is set to false if the string is not a
576
number, is out of range, or if it has trailing garbage; otherwise
577
*\a ok is set to true.
580
short Q3CString::toShort(bool *ok) const
583
if (ok && *ok && (v < -32768 || v > 32767))
589
Returns the string converted to an \c{unsigned short} value.
591
If \a ok is not 0: *\a ok is set to false if the string is not a
592
number, is out of range, or if it has trailing garbage; otherwise
593
*\a ok is set to true.
596
ushort Q3CString::toUShort(bool *ok) const
598
ulong v = toULong(ok);
599
if (ok && *ok && (v > 65535))
606
Returns the string converted to a \c{int} value.
608
If \a ok is not 0: *\a ok is set to false if the string is not a
609
number, or if it has trailing garbage; otherwise *\a ok is set to
613
int Q3CString::toInt(bool *ok) const
615
return (int)toLong(ok);
619
Returns the string converted to an \c{unsigned int} value.
621
If \a ok is not 0: *\a ok is set to false if the string is not a
622
number, or if it has trailing garbage; otherwise *\a ok is set to
626
uint Q3CString::toUInt(bool *ok) const
628
return (uint)toULong(ok);
632
Returns the string converted to a \c{double} value.
634
If \a ok is not 0: *\a ok is set to false if the string is not a
635
number, or if it has trailing garbage; otherwise *\a ok is set to
639
double Q3CString::toDouble(bool *ok) const
642
double val = strtod(constData() ? constData() : "", &end);
644
*ok = (constData() && *constData() && (end == 0 || *end == '\0'));
649
Returns the string converted to a \c{float} value.
651
If \a ok is not 0: *\a ok is set to false if the string is not a
652
number, or if it has trailing garbage; otherwise *\a ok is set to
656
float Q3CString::toFloat(bool *ok) const
658
return (float)toDouble(ok);
662
/*! \fn Q3CString &Q3CString::setStr(const char *str)
663
Makes a deep copy of \a str. Returns a reference to the string.
669
Sets the string to the string representation of the number \a n
670
and returns a reference to the string.
673
Q3CString &Q3CString::setNum(long n)
677
register char *p = &buf[19];
687
*--p = ((int)(n%10)) + '0';
699
Sets the string to the string representation of the number \a n
700
and returns a reference to the string.
703
Q3CString &Q3CString::setNum(ulong n)
707
register char *p = &buf[19];
710
*--p = ((int)(n%10)) + '0';
718
\fn Q3CString &Q3CString::setNum(int n)
721
Sets the string to the string representation of the number \a n
722
and returns a reference to the string.
726
\fn Q3CString &Q3CString::setNum(uint n)
729
Sets the string to the string representation of the number \a n
730
and returns a reference to the string.
734
\fn Q3CString &Q3CString::setNum(short n)
737
Sets the string to the string representation of the number \a n
738
and returns a reference to the string.
742
\fn Q3CString &Q3CString::setNum(ushort n)
745
Sets the string to the string representation of the number \a n
746
and returns a reference to the string.
750
Sets the string to the string representation of the number \a n
751
and returns a reference to the string.
753
The format of the string representation is specified by the format
754
character \a f, and the precision (number of digits after the
755
decimal point) is specified with \a prec.
757
The valid formats for \a f are 'e', 'E', 'f', 'g' and 'G'. The
758
formats are the same as for sprintf(); they are explained in \l
762
Q3CString &Q3CString::setNum(double n, char f, int prec)
765
if (!(f=='f' || f=='F' || f=='e' || f=='E' || f=='g' || f=='G'))
766
qWarning("Q3CString::setNum: Invalid format char '%c'", f);
769
register char *fs = format; // generate format string
770
*fs++ = '%'; // "%.<prec>l<f>"
775
*fs++ = prec / 10 + '0';
776
*fs++ = prec % 10 + '0';
783
return sprintf(format, n);
786
/*! \fn Q3CString &Q3CString::setNum(float n, char f, int prec)
791
Sets the character at position \a index to \a c and expands the
792
string if necessary, padding with spaces.
794
Returns false if \a index was out of range and the string could
795
not be expanded; otherwise returns true.
798
bool Q3CString::setExpand(uint index, char c)
800
uint oldlen = length();
801
if (index >= oldlen) {
804
memset(data() + oldlen, ' ', index - oldlen);
806
*(data() + index) = c;
812
\fn Q3CString::operator const char *() const
814
Returns the string data.
819
\fn Q3CString& Q3CString::append(const char *str)
821
Appends string \a str to the string and returns a reference to the
822
string. Equivalent to operator+=().
827
/*! \fn QDataStream &operator<<(QDataStream &s, const Q3CString &str)
830
Writes string \a str to the stream \a s.
832
\sa \link datastreamformat.html Format of the QDataStream operators \endlink
836
\fn QDataStream &operator>>(QDataStream &s, Q3CString &str)
839
Reads a string into \a str from the stream \a s.
841
\sa \link datastreamformat.html Format of the QDataStream operators \endlink
844
/*****************************************************************************
845
Documentation for related functions
846
*****************************************************************************/
849
\fn bool operator==(const Q3CString &s1, const Q3CString &s2)
853
Returns true if \a s1 and \a s2 are equal; otherwise returns false.
855
Equivalent to qstrcmp(\a s1, \a s2) == 0.
859
\fn bool operator==(const Q3CString &s1, const char *s2)
864
Returns true if \a s1 and \a s2 are equal; otherwise returns false.
866
Equivalent to qstrcmp(\a s1, \a s2) == 0.
870
\fn bool operator==(const char *s1, const Q3CString &s2)
875
Returns true if \a s1 and \a s2 are equal; otherwise returns false.
877
Equivalent to qstrcmp(\a s1, \a s2) == 0.
881
\fn bool operator!=(const Q3CString &s1, const Q3CString &s2)
885
Returns true if \a s1 and \a s2 are different; otherwise returns false.
887
Equivalent to qstrcmp(\a s1, \a s2) != 0.
891
\fn bool operator!=(const Q3CString &s1, const char *s2)
896
Returns true if \a s1 and \a s2 are different; otherwise returns false.
898
Equivalent to qstrcmp(\a s1, \a s2) != 0.
902
\fn bool operator!=(const char *s1, const Q3CString &s2)
907
Returns true if \a s1 and \a s2 are different; otherwise returns false.
909
Equivalent to qstrcmp(\a s1, \a s2) != 0.
913
\fn bool operator<(const Q3CString &s1, const char *s2)
917
Returns true if \a s1 is less than \a s2; otherwise returns false.
919
Equivalent to qstrcmp(\a s1, \a s2) \< 0.
923
\fn bool operator<(const char *s1, const Q3CString &s2)
928
Returns true if \a s1 is less than \a s2; otherwise returns false.
930
Equivalent to qstrcmp(\a s1, \a s2) \< 0.
934
\fn bool operator<=(const Q3CString &s1, const char *s2)
938
Returns true if \a s1 is less than or equal to \a s2; otherwise
941
Equivalent to qstrcmp(\a s1, \a s2) \<= 0.
945
\fn bool operator<=(const char *s1, const Q3CString &s2)
950
Returns true if \a s1 is less than or equal to \a s2; otherwise
953
Equivalent to qstrcmp(\a s1, \a s2) \<= 0.
957
\fn bool operator>(const Q3CString &s1, const char *s2)
961
Returns true if \a s1 is greater than \a s2; otherwise returns false.
963
Equivalent to qstrcmp(\a s1, \a s2) \> 0.
967
\fn bool operator>(const char *s1, const Q3CString &s2)
972
Returns true if \a s1 is greater than \a s2; otherwise returns false.
974
Equivalent to qstrcmp(\a s1, \a s2) \> 0.
978
\fn bool operator>=(const Q3CString &s1, const char *s2)
982
Returns true if \a s1 is greater than or equal to \a s2; otherwise
985
Equivalent to qstrcmp(\a s1, \a s2) \>= 0.
989
\fn bool operator>=(const char *s1, const Q3CString &s2)
994
Returns true if \a s1 is greater than or equal to \a s2; otherwise
997
Equivalent to qstrcmp(\a s1, \a s2) \>= 0.
1001
\fn const Q3CString operator+(const Q3CString &s1, const Q3CString &s2)
1005
Returns a string which consists of the concatenation of \a s1 and
1010
\fn const Q3CString operator+(const Q3CString &s1, const char *s2)
1015
Returns a string which consists of the concatenation of \a s1 and \a s2.
1019
\fn const Q3CString operator+(const char *s1, const Q3CString &s2)
1024
Returns a string which consists of the concatenation of \a s1 and \a s2.
1028
\fn const Q3CString operator+(const Q3CString &s, char c)
1033
Returns a string which consists of the concatenation of \a s and \a c.
1037
\fn const Q3CString operator+(char c, const Q3CString &s)
1042
Returns a string which consists of the concatenation of \a c and \a s.