1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/string.cpp
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin, Ryan Norton
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // (c) 2004 Ryan Norton <wxprojects@comcast.net>
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
15 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
16 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
17 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
20 // ===========================================================================
21 // headers, declarations, constants
22 // ===========================================================================
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
32 #include "wx/string.h"
48 #include <wx/hashmap.h>
50 // string handling functions used by wxString:
51 #if wxUSE_UNICODE_UTF8
52 #define wxStringMemcpy memcpy
53 #define wxStringMemcmp memcmp
54 #define wxStringMemchr memchr
55 #define wxStringStrlen strlen
57 #define wxStringMemcpy wxTmemcpy
58 #define wxStringMemcmp wxTmemcmp
59 #define wxStringMemchr wxTmemchr
60 #define wxStringStrlen wxStrlen
64 // ---------------------------------------------------------------------------
65 // static class variables definition
66 // ---------------------------------------------------------------------------
68 //According to STL _must_ be a -1 size_t
69 const size_t wxString::npos
= (size_t) -1;
71 // ----------------------------------------------------------------------------
73 // ----------------------------------------------------------------------------
75 #if wxUSE_STD_IOSTREAM
79 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxCStrData
& str
)
81 // FIXME-UTF8: always, not only if wxUSE_UNICODE
82 #if wxUSE_UNICODE && !defined(__BORLANDC__)
83 return os
<< str
.AsWChar();
85 return os
<< str
.AsChar();
89 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
91 return os
<< str
.c_str();
94 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxCharBuffer
& str
)
96 return os
<< str
.data();
100 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxWCharBuffer
& str
)
102 return os
<< str
.data();
106 #endif // wxUSE_STD_IOSTREAM
108 // ----------------------------------------------------------------------------
109 // wxCStrData converted strings caching
110 // ----------------------------------------------------------------------------
112 // For backward compatibility reasons, it must be possible to assign the value
113 // returned by wxString::c_str() to a char* or wchar_t* variable and work with
114 // it. Returning wxCharBuffer from (const char*)c_str() wouldn't do the trick,
115 // because the memory would be freed immediately, but it has to be valid as long
116 // as the string is not modified, so that code like this still works:
118 // const wxChar *s = str.c_str();
119 // while ( s ) { ... }
121 // FIXME-UTF8: not thread safe!
122 // FIXME-UTF8: we currently clear the cached conversion only when the string is
123 // destroyed, but we should do it when the string is modified, to
124 // keep memory usage down
125 // FIXME-UTF8: we do the conversion every time As[W]Char() is called, but if we
126 // invalidated the cache on every change, we could keep the previous
128 // FIXME-UTF8: add tracing of usage of these two methods - new code is supposed
129 // to use mb_str() or wc_str() instead of (const [w]char*)c_str()
132 static inline void DeleteStringFromConversionCache(T
& hash
, const wxString
*s
)
134 typename
T::iterator i
= hash
.find(wxConstCast(s
, wxString
));
135 if ( i
!= hash
.end() )
143 // NB: non-STL implementation doesn't compile with "const wxString*" key type,
144 // so we have to use wxString* here and const-cast when used
145 WX_DECLARE_HASH_MAP(wxString
*, char*, wxPointerHash
, wxPointerEqual
,
146 wxStringCharConversionCache
);
147 static wxStringCharConversionCache gs_stringsCharCache
;
149 const char* wxCStrData::AsChar() const
151 // remove previously cache value, if any (see FIXMEs above):
152 DeleteStringFromConversionCache(gs_stringsCharCache
, m_str
);
154 // convert the string and keep it:
155 const char *s
= gs_stringsCharCache
[wxConstCast(m_str
, wxString
)] =
156 m_str
->mb_str().release();
160 #endif // wxUSE_UNICODE
162 #if !wxUSE_UNICODE_WCHAR
163 WX_DECLARE_HASH_MAP(wxString
*, wchar_t*, wxPointerHash
, wxPointerEqual
,
164 wxStringWCharConversionCache
);
165 static wxStringWCharConversionCache gs_stringsWCharCache
;
167 const wchar_t* wxCStrData::AsWChar() const
169 // remove previously cache value, if any (see FIXMEs above):
170 DeleteStringFromConversionCache(gs_stringsWCharCache
, m_str
);
172 // convert the string and keep it:
173 const wchar_t *s
= gs_stringsWCharCache
[wxConstCast(m_str
, wxString
)] =
174 m_str
->wc_str().release();
178 #endif // !wxUSE_UNICODE_WCHAR
180 // ===========================================================================
181 // wxString class core
182 // ===========================================================================
184 // ---------------------------------------------------------------------------
185 // construction and conversion
186 // ---------------------------------------------------------------------------
188 wxString::~wxString()
191 // FIXME-UTF8: do this only if locale is not UTF8 if wxUSE_UNICODE_UTF8
192 DeleteStringFromConversionCache(gs_stringsCharCache
, this);
194 #if !wxUSE_UNICODE_WCHAR
195 DeleteStringFromConversionCache(gs_stringsWCharCache
, this);
201 wxString::SubstrBufFromMB
wxString::ConvertStr(const char *psz
, size_t nLength
,
202 const wxMBConv
& conv
)
205 if ( !psz
|| nLength
== 0 )
206 return SubstrBufFromMB();
208 if ( nLength
== npos
)
212 wxWCharBuffer
wcBuf(conv
.cMB2WC(psz
, nLength
, &wcLen
));
214 return SubstrBufFromMB();
216 return SubstrBufFromMB(wcBuf
, wcLen
);
220 wxString::SubstrBufFromWC
wxString::ConvertStr(const wchar_t *pwz
, size_t nLength
,
221 const wxMBConv
& conv
)
224 if ( !pwz
|| nLength
== 0 )
225 return SubstrBufFromWC();
227 if ( nLength
== npos
)
231 wxCharBuffer
mbBuf(conv
.cWC2MB(pwz
, nLength
, &mbLen
));
233 return SubstrBufFromWC();
235 return SubstrBufFromWC(mbBuf
, mbLen
);
242 //Convert wxString in Unicode mode to a multi-byte string
243 const wxCharBuffer
wxString::mb_str(const wxMBConv
& conv
) const
245 return conv
.cWC2MB(c_str(), length() + 1 /* size, not length */, NULL
);
252 //Converts this string to a wide character string if unicode
253 //mode is not enabled and wxUSE_WCHAR_T is enabled
254 const wxWCharBuffer
wxString::wc_str(const wxMBConv
& conv
) const
256 return conv
.cMB2WC(c_str(), length() + 1 /* size, not length */, NULL
);
259 #endif // wxUSE_WCHAR_T
261 #endif // Unicode/ANSI
263 // shrink to minimal size (releasing extra memory)
264 bool wxString::Shrink()
266 wxString
tmp(begin(), end());
268 return tmp
.length() == length();
271 // deprecated compatibility code:
272 #if WXWIN_COMPATIBILITY_2_8 && !wxUSE_STL_BASED_WXSTRING && !wxUSE_UNICODE_UTF8
273 wxChar
*wxString::GetWriteBuf(size_t nLen
)
275 return DoGetWriteBuf(nLen
);
278 void wxString::UngetWriteBuf()
283 void wxString::UngetWriteBuf(size_t nLen
)
285 DoUngetWriteBuf(nLen
);
287 #endif // WXWIN_COMPATIBILITY_2_8 && !wxUSE_STL_BASED_WXSTRING && !wxUSE_UNICODE_UTF8
290 // ---------------------------------------------------------------------------
292 // ---------------------------------------------------------------------------
294 // all functions are inline in string.h
296 // ---------------------------------------------------------------------------
297 // concatenation operators
298 // ---------------------------------------------------------------------------
301 * concatenation functions come in 5 flavours:
303 * char + string and string + char
304 * C str + string and string + C str
307 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
309 #if !wxUSE_STL_BASED_WXSTRING
310 wxASSERT( str1
.IsValid() );
311 wxASSERT( str2
.IsValid() );
320 wxString
operator+(const wxString
& str
, wxUniChar ch
)
322 #if !wxUSE_STL_BASED_WXSTRING
323 wxASSERT( str
.IsValid() );
332 wxString
operator+(wxUniChar ch
, const wxString
& str
)
334 #if !wxUSE_STL_BASED_WXSTRING
335 wxASSERT( str
.IsValid() );
344 wxString
operator+(const wxString
& str
, const char *psz
)
346 #if !wxUSE_STL_BASED_WXSTRING
347 wxASSERT( str
.IsValid() );
351 if ( !s
.Alloc(strlen(psz
) + str
.length()) ) {
352 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
360 wxString
operator+(const wxString
& str
, const wchar_t *pwz
)
362 #if !wxUSE_STL_BASED_WXSTRING
363 wxASSERT( str
.IsValid() );
367 if ( !s
.Alloc(wxWcslen(pwz
) + str
.length()) ) {
368 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
376 wxString
operator+(const char *psz
, const wxString
& str
)
378 #if !wxUSE_STL_BASED_WXSTRING
379 wxASSERT( str
.IsValid() );
383 if ( !s
.Alloc(strlen(psz
) + str
.length()) ) {
384 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
392 wxString
operator+(const wchar_t *pwz
, const wxString
& str
)
394 #if !wxUSE_STL_BASED_WXSTRING
395 wxASSERT( str
.IsValid() );
399 if ( !s
.Alloc(wxWcslen(pwz
) + str
.length()) ) {
400 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
408 // ---------------------------------------------------------------------------
410 // ---------------------------------------------------------------------------
412 #ifdef HAVE_STD_STRING_COMPARE
414 // NB: Comparison code (both if HAVE_STD_STRING_COMPARE and if not) works with
415 // UTF-8 encoded strings too, thanks to UTF-8's design which allows us to
416 // sort strings in characters code point order by sorting the byte sequence
417 // in byte values order (i.e. what strcmp() and memcmp() do).
419 int wxString::compare(const wxString
& str
) const
421 return m_impl
.compare(str
.m_impl
);
424 int wxString::compare(size_t nStart
, size_t nLen
,
425 const wxString
& str
) const
428 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
429 return m_impl
.compare(pos
, len
, str
.m_impl
);
432 int wxString::compare(size_t nStart
, size_t nLen
,
434 size_t nStart2
, size_t nLen2
) const
437 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
440 str
.PosLenToImpl(nStart2
, nLen2
, &pos2
, &len2
);
442 return m_impl
.compare(pos
, len
, str
.m_impl
, pos2
, len2
);
445 int wxString::compare(const char* sz
) const
447 return m_impl
.compare(ImplStr(sz
));
450 int wxString::compare(const wchar_t* sz
) const
452 return m_impl
.compare(ImplStr(sz
));
455 int wxString::compare(size_t nStart
, size_t nLen
,
456 const char* sz
, size_t nCount
) const
459 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
461 SubstrBufFromMB
str(ImplStr(sz
, nCount
));
463 return m_impl
.compare(pos
, len
, str
.data
, str
.len
);
466 int wxString::compare(size_t nStart
, size_t nLen
,
467 const wchar_t* sz
, size_t nCount
) const
470 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
472 SubstrBufFromWC
str(ImplStr(sz
, nCount
));
474 return m_impl
.compare(pos
, len
, str
.data
, str
.len
);
477 #else // !HAVE_STD_STRING_COMPARE
479 static inline int wxDoCmp(const wxStringCharType
* s1
, size_t l1
,
480 const wxStringCharType
* s2
, size_t l2
)
483 return wxStringMemcmp(s1
, s2
, l1
);
486 int ret
= wxStringMemcmp(s1
, s2
, l1
);
487 return ret
== 0 ? -1 : ret
;
491 int ret
= wxStringMemcmp(s1
, s2
, l2
);
492 return ret
== 0 ? +1 : ret
;
496 int wxString::compare(const wxString
& str
) const
498 return ::wxDoCmp(m_impl
.data(), m_impl
.length(),
499 str
.m_impl
.data(), str
.m_impl
.length());
502 int wxString::compare(size_t nStart
, size_t nLen
,
503 const wxString
& str
) const
505 wxASSERT(nStart
<= length());
506 size_type strLen
= length() - nStart
;
507 nLen
= strLen
< nLen
? strLen
: nLen
;
510 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
512 return ::wxDoCmp(m_impl
.data() + pos
, len
,
513 str
.m_impl
.data(), str
.m_impl
.length());
516 int wxString::compare(size_t nStart
, size_t nLen
,
518 size_t nStart2
, size_t nLen2
) const
520 wxASSERT(nStart
<= length());
521 wxASSERT(nStart2
<= str
.length());
522 size_type strLen
= length() - nStart
,
523 strLen2
= str
.length() - nStart2
;
524 nLen
= strLen
< nLen
? strLen
: nLen
;
525 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
528 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
530 str
.PosLenToImpl(nStart2
, nLen2
, &pos2
, &len2
);
532 return ::wxDoCmp(m_impl
.data() + pos
, len
,
533 str
.m_impl
.data() + pos2
, len2
);
536 int wxString::compare(const char* sz
) const
538 SubstrBufFromMB
str(ImplStr(sz
, npos
));
539 if ( str
.len
== npos
)
540 str
.len
= wxStringStrlen(str
.data
);
541 return ::wxDoCmp(m_impl
.data(), m_impl
.length(), str
.data
, str
.len
);
544 int wxString::compare(const wchar_t* sz
) const
546 SubstrBufFromWC
str(ImplStr(sz
, npos
));
547 if ( str
.len
== npos
)
548 str
.len
= wxStringStrlen(str
.data
);
549 return ::wxDoCmp(m_impl
.data(), m_impl
.length(), str
.data
, str
.len
);
552 int wxString::compare(size_t nStart
, size_t nLen
,
553 const char* sz
, size_t nCount
) const
555 wxASSERT(nStart
<= length());
556 size_type strLen
= length() - nStart
;
557 nLen
= strLen
< nLen
? strLen
: nLen
;
560 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
562 SubstrBufFromMB
str(ImplStr(sz
, nCount
));
563 if ( str
.len
== npos
)
564 str
.len
= wxStringStrlen(str
.data
);
566 return ::wxDoCmp(m_impl
.data() + pos
, len
, str
.data
, str
.len
);
569 int wxString::compare(size_t nStart
, size_t nLen
,
570 const wchar_t* sz
, size_t nCount
) const
572 wxASSERT(nStart
<= length());
573 size_type strLen
= length() - nStart
;
574 nLen
= strLen
< nLen
? strLen
: nLen
;
577 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
579 SubstrBufFromWC
str(ImplStr(sz
, nCount
));
580 if ( str
.len
== npos
)
581 str
.len
= wxStringStrlen(str
.data
);
583 return ::wxDoCmp(m_impl
.data() + pos
, len
, str
.data
, str
.len
);
586 #endif // HAVE_STD_STRING_COMPARE/!HAVE_STD_STRING_COMPARE
589 // ---------------------------------------------------------------------------
590 // find_{first,last}_[not]_of functions
591 // ---------------------------------------------------------------------------
593 #if !wxUSE_STL_BASED_WXSTRING || wxUSE_UNICODE_UTF8
595 // NB: All these functions are implemented with the argument being wxChar*,
596 // i.e. widechar string in any Unicode build, even though native string
597 // representation is char* in the UTF-8 build. This is because we couldn't
598 // use memchr() to determine if a character is in a set encoded as UTF-8.
600 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
602 return find_first_of(sz
, nStart
, wxStrlen(sz
));
605 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
607 return find_first_not_of(sz
, nStart
, wxStrlen(sz
));
610 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
612 wxASSERT_MSG( nStart
<= length(), _T("invalid index") );
615 for ( const_iterator i
= begin() + nStart
; i
!= end(); ++idx
, ++i
)
617 if ( wxTmemchr(sz
, *i
, n
) )
624 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
626 wxASSERT_MSG( nStart
<= length(), _T("invalid index") );
629 for ( const_iterator i
= begin() + nStart
; i
!= end(); ++idx
, ++i
)
631 if ( !wxTmemchr(sz
, *i
, n
) )
639 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
641 return find_last_of(sz
, nStart
, wxStrlen(sz
));
644 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
646 return find_last_not_of(sz
, nStart
, wxStrlen(sz
));
649 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
651 size_t len
= length();
653 if ( nStart
== npos
)
659 wxASSERT_MSG( nStart
<= len
, _T("invalid index") );
663 for ( const_reverse_iterator i
= rbegin() + (len
- nStart
- 1);
664 i
!= rend(); --idx
, ++i
)
666 if ( wxTmemchr(sz
, *i
, n
) )
673 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
675 size_t len
= length();
677 if ( nStart
== npos
)
683 wxASSERT_MSG( nStart
<= len
, _T("invalid index") );
687 for ( const_reverse_iterator i
= rbegin() + (len
- nStart
- 1);
688 i
!= rend(); --idx
, ++i
)
690 if ( !wxTmemchr(sz
, *i
, n
) )
697 size_t wxString::find_first_not_of(wxUniChar ch
, size_t nStart
) const
699 wxASSERT_MSG( nStart
<= length(), _T("invalid index") );
702 for ( const_iterator i
= begin() + nStart
; i
!= end(); ++idx
, ++i
)
711 size_t wxString::find_last_not_of(wxUniChar ch
, size_t nStart
) const
713 size_t len
= length();
715 if ( nStart
== npos
)
721 wxASSERT_MSG( nStart
<= len
, _T("invalid index") );
725 for ( const_reverse_iterator i
= rbegin() + (len
- nStart
- 1);
726 i
!= rend(); --idx
, ++i
)
735 // the functions above were implemented for wchar_t* arguments in Unicode
736 // build and char* in ANSI build; below are implementations for the other
739 #define wxOtherCharType char
740 #define STRCONV (const wxChar*)wxConvLibc.cMB2WC
742 #define wxOtherCharType wchar_t
743 #define STRCONV (const wxChar*)wxConvLibc.cWC2MB
746 size_t wxString::find_first_of(const wxOtherCharType
* sz
, size_t nStart
) const
747 { return find_first_of(STRCONV(sz
), nStart
); }
749 size_t wxString::find_first_of(const wxOtherCharType
* sz
, size_t nStart
,
751 { return find_first_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
752 size_t wxString::find_last_of(const wxOtherCharType
* sz
, size_t nStart
) const
753 { return find_last_of(STRCONV(sz
), nStart
); }
754 size_t wxString::find_last_of(const wxOtherCharType
* sz
, size_t nStart
,
756 { return find_last_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
757 size_t wxString::find_first_not_of(const wxOtherCharType
* sz
, size_t nStart
) const
758 { return find_first_not_of(STRCONV(sz
), nStart
); }
759 size_t wxString::find_first_not_of(const wxOtherCharType
* sz
, size_t nStart
,
761 { return find_first_not_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
762 size_t wxString::find_last_not_of(const wxOtherCharType
* sz
, size_t nStart
) const
763 { return find_last_not_of(STRCONV(sz
), nStart
); }
764 size_t wxString::find_last_not_of(const wxOtherCharType
* sz
, size_t nStart
,
766 { return find_last_not_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
768 #undef wxOtherCharType
771 #endif // !wxUSE_STL_BASED_WXSTRING || wxUSE_UNICODE_UTF8
773 // ===========================================================================
774 // other common string functions
775 // ===========================================================================
777 int wxString::CmpNoCase(const wxString
& s
) const
779 // FIXME-UTF8: use wxUniChar::ToLower/ToUpper once added
782 const_iterator i1
= begin();
783 const_iterator end1
= end();
784 const_iterator i2
= s
.begin();
785 const_iterator end2
= s
.end();
787 for ( ; i1
!= end1
&& i2
!= end2
; ++idx
, ++i1
, ++i2
)
789 wxUniChar lower1
= (wxChar
)wxTolower(*i1
);
790 wxUniChar lower2
= (wxChar
)wxTolower(*i2
);
791 if ( lower1
!= lower2
)
792 return lower1
< lower2
? -1 : 1;
795 size_t len1
= length();
796 size_t len2
= s
.length();
800 else if ( len1
> len2
)
809 #ifndef __SCHAR_MAX__
810 #define __SCHAR_MAX__ 127
814 wxString
wxString::FromAscii(const char *ascii
)
817 return wxEmptyString
;
819 size_t len
= strlen( ascii
);
824 wxStringBuffer
buf(res
, len
);
830 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
838 wxString
wxString::FromAscii(const char ascii
)
840 // What do we do with '\0' ?
843 res
+= (wchar_t)(unsigned char) ascii
;
848 const wxCharBuffer
wxString::ToAscii() const
850 // this will allocate enough space for the terminating NUL too
851 wxCharBuffer
buffer(length());
854 char *dest
= buffer
.data();
856 const wchar_t *pwc
= c_str();
859 *dest
++ = (char)(*pwc
> SCHAR_MAX
? wxT('_') : *pwc
);
861 // the output string can't have embedded NULs anyhow, so we can safely
862 // stop at first of them even if we do have any
872 // extract string of length nCount starting at nFirst
873 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
875 size_t nLen
= length();
877 // default value of nCount is npos and means "till the end"
878 if ( nCount
== npos
)
880 nCount
= nLen
- nFirst
;
883 // out-of-bounds requests return sensible things
884 if ( nFirst
+ nCount
> nLen
)
886 nCount
= nLen
- nFirst
;
891 // AllocCopy() will return empty string
892 return wxEmptyString
;
895 wxString
dest(*this, nFirst
, nCount
);
896 if ( dest
.length() != nCount
)
898 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
904 // check that the string starts with prefix and return the rest of the string
905 // in the provided pointer if it is not NULL, otherwise return false
906 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
908 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
910 // first check if the beginning of the string matches the prefix: note
911 // that we don't have to check that we don't run out of this string as
912 // when we reach the terminating NUL, either prefix string ends too (and
913 // then it's ok) or we break out of the loop because there is no match
914 const wxChar
*p
= c_str();
917 if ( *prefix
++ != *p
++ )
926 // put the rest of the string into provided pointer
934 // check that the string ends with suffix and return the rest of it in the
935 // provided pointer if it is not NULL, otherwise return false
936 bool wxString::EndsWith(const wxChar
*suffix
, wxString
*rest
) const
938 wxASSERT_MSG( suffix
, _T("invalid parameter in wxString::EndssWith") );
940 int start
= length() - wxStrlen(suffix
);
941 if ( start
< 0 || wxStrcmp(wx_str() + start
, suffix
) != 0 )
946 // put the rest of the string into provided pointer
947 rest
->assign(*this, 0, start
);
954 // extract nCount last (rightmost) characters
955 wxString
wxString::Right(size_t nCount
) const
957 if ( nCount
> length() )
960 wxString
dest(*this, length() - nCount
, nCount
);
961 if ( dest
.length() != nCount
) {
962 wxFAIL_MSG( _T("out of memory in wxString::Right") );
967 // get all characters after the last occurence of ch
968 // (returns the whole string if ch not found)
969 wxString
wxString::AfterLast(wxUniChar ch
) const
972 int iPos
= Find(ch
, true);
973 if ( iPos
== wxNOT_FOUND
)
976 str
= wx_str() + iPos
+ 1;
981 // extract nCount first (leftmost) characters
982 wxString
wxString::Left(size_t nCount
) const
984 if ( nCount
> length() )
987 wxString
dest(*this, 0, nCount
);
988 if ( dest
.length() != nCount
) {
989 wxFAIL_MSG( _T("out of memory in wxString::Left") );
994 // get all characters before the first occurence of ch
995 // (returns the whole string if ch not found)
996 wxString
wxString::BeforeFirst(wxUniChar ch
) const
999 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1000 return wxString(*this, 0, iPos
);
1003 /// get all characters before the last occurence of ch
1004 /// (returns empty string if ch not found)
1005 wxString
wxString::BeforeLast(wxUniChar ch
) const
1008 int iPos
= Find(ch
, true);
1009 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1010 str
= wxString(c_str(), iPos
);
1015 /// get all characters after the first occurence of ch
1016 /// (returns empty string if ch not found)
1017 wxString
wxString::AfterFirst(wxUniChar ch
) const
1020 int iPos
= Find(ch
);
1021 if ( iPos
!= wxNOT_FOUND
)
1022 str
= wx_str() + iPos
+ 1;
1027 // replace first (or all) occurences of some substring with another one
1028 size_t wxString::Replace(const wxString
& strOld
,
1029 const wxString
& strNew
, bool bReplaceAll
)
1031 // if we tried to replace an empty string we'd enter an infinite loop below
1032 wxCHECK_MSG( !strOld
.empty(), 0,
1033 _T("wxString::Replace(): invalid parameter") );
1035 size_t uiCount
= 0; // count of replacements made
1037 size_t uiOldLen
= strOld
.length();
1038 size_t uiNewLen
= strNew
.length();
1042 while ( (*this)[dwPos
] != wxT('\0') )
1044 //DO NOT USE STRSTR HERE
1045 //this string can contain embedded null characters,
1046 //so strstr will function incorrectly
1047 dwPos
= find(strOld
, dwPos
);
1048 if ( dwPos
== npos
)
1049 break; // exit the loop
1052 //replace this occurance of the old string with the new one
1053 replace(dwPos
, uiOldLen
, strNew
, uiNewLen
);
1055 //move up pos past the string that was replaced
1058 //increase replace count
1063 break; // exit the loop
1070 bool wxString::IsAscii() const
1072 const wxChar
*s
= (const wxChar
*) *this;
1074 if(!isascii(*s
)) return(false);
1080 bool wxString::IsWord() const
1082 const wxChar
*s
= (const wxChar
*) *this;
1084 if(!wxIsalpha(*s
)) return(false);
1090 bool wxString::IsNumber() const
1092 const wxChar
*s
= (const wxChar
*) *this;
1094 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1096 if(!wxIsdigit(*s
)) return(false);
1102 wxString
wxString::Strip(stripType w
) const
1105 if ( w
& leading
) s
.Trim(false);
1106 if ( w
& trailing
) s
.Trim(true);
1110 // ---------------------------------------------------------------------------
1112 // ---------------------------------------------------------------------------
1114 wxString
& wxString::MakeUpper()
1116 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1117 *it
= (wxChar
)wxToupper(*it
);
1122 wxString
& wxString::MakeLower()
1124 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1125 *it
= (wxChar
)wxTolower(*it
);
1130 // ---------------------------------------------------------------------------
1131 // trimming and padding
1132 // ---------------------------------------------------------------------------
1134 // some compilers (VC++ 6.0 not to name them) return true for a call to
1135 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1136 // live with this by checking that the character is a 7 bit one - even if this
1137 // may fail to detect some spaces (I don't know if Unicode doesn't have
1138 // space-like symbols somewhere except in the first 128 chars), it is arguably
1139 // still better than trimming away accented letters
1140 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1142 // trims spaces (in the sense of isspace) from left or right side
1143 wxString
& wxString::Trim(bool bFromRight
)
1145 // first check if we're going to modify the string at all
1148 (bFromRight
&& wxSafeIsspace(GetChar(length() - 1))) ||
1149 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1155 // find last non-space character
1156 reverse_iterator psz
= rbegin();
1157 while ( (psz
!= rend()) && wxSafeIsspace(*psz
) )
1160 // truncate at trailing space start
1161 erase(psz
.base(), end());
1165 // find first non-space character
1166 iterator psz
= begin();
1167 while ( (psz
!= end()) && wxSafeIsspace(*psz
) )
1170 // fix up data and length
1171 erase(begin(), psz
);
1178 // adds nCount characters chPad to the string from either side
1179 wxString
& wxString::Pad(size_t nCount
, wxUniChar chPad
, bool bFromRight
)
1181 wxString
s(chPad
, nCount
);
1194 // truncate the string
1195 wxString
& wxString::Truncate(size_t uiLen
)
1197 if ( uiLen
< length() )
1199 erase(begin() + uiLen
, end());
1201 //else: nothing to do, string is already short enough
1206 // ---------------------------------------------------------------------------
1207 // finding (return wxNOT_FOUND if not found and index otherwise)
1208 // ---------------------------------------------------------------------------
1211 int wxString::Find(wxUniChar ch
, bool bFromEnd
) const
1213 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1215 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1218 // ----------------------------------------------------------------------------
1219 // conversion to numbers
1220 // ----------------------------------------------------------------------------
1222 // the implementation of all the functions below is exactly the same so factor
1225 template <typename T
, typename F
>
1226 bool wxStringToIntType(const wxChar
*start
,
1231 wxCHECK_MSG( val
, false, _T("NULL output pointer") );
1232 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1239 *val
= (*func
)(start
, &end
, base
);
1241 // return true only if scan was stopped by the terminating NUL and if the
1242 // string was not empty to start with and no under/overflow occurred
1243 return !*end
&& (end
!= start
)
1245 && (errno
!= ERANGE
)
1250 bool wxString::ToLong(long *val
, int base
) const
1252 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtol
);
1255 bool wxString::ToULong(unsigned long *val
, int base
) const
1257 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtoul
);
1260 bool wxString::ToLongLong(wxLongLong_t
*val
, int base
) const
1262 #ifdef wxHAS_STRTOLL
1263 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtoll
);
1265 // TODO: implement this ourselves
1269 #endif // wxHAS_STRTOLL
1272 bool wxString::ToULongLong(wxULongLong_t
*val
, int base
) const
1274 #ifdef wxHAS_STRTOLL
1275 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtoull
);
1277 // TODO: implement this ourselves
1284 bool wxString::ToDouble(double *val
) const
1286 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1292 const wxChar
*start
= c_str();
1294 *val
= wxStrtod(start
, &end
);
1296 // return true only if scan was stopped by the terminating NUL and if the
1297 // string was not empty to start with and no under/overflow occurred
1298 return !*end
&& (end
!= start
)
1300 && (errno
!= ERANGE
)
1305 // ---------------------------------------------------------------------------
1307 // ---------------------------------------------------------------------------
1310 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1311 wxString
wxStringPrintfMixinBase::DoFormat(const wxChar
*format
, ...)
1313 wxString
wxString::DoFormat(const wxChar
*format
, ...)
1317 va_start(argptr
, format
);
1320 s
.PrintfV(format
, argptr
);
1328 wxString
wxString::FormatV(const wxString
& format
, va_list argptr
)
1331 s
.PrintfV(format
, argptr
);
1335 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1336 int wxStringPrintfMixinBase::DoPrintf(const wxChar
*format
, ...)
1338 int wxString::DoPrintf(const wxChar
*format
, ...)
1342 va_start(argptr
, format
);
1344 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1345 // get a pointer to the wxString instance; we have to use dynamic_cast<>
1346 // because it's the only cast that works safely for downcasting when
1347 // multiple inheritance is used:
1348 wxString
*str
= static_cast<wxString
*>(this);
1350 wxString
*str
= this;
1353 int iLen
= str
->PrintfV(format
, argptr
);
1360 int wxString::PrintfV(const wxString
& format
, va_list argptr
)
1366 wxStringBuffer
tmp(*this, size
+ 1);
1375 // wxVsnprintf() may modify the original arg pointer, so pass it
1378 wxVaCopy(argptrcopy
, argptr
);
1379 int len
= wxVsnprintf(buf
, size
, format
, argptrcopy
);
1382 // some implementations of vsnprintf() don't NUL terminate
1383 // the string if there is not enough space for it so
1384 // always do it manually
1385 buf
[size
] = _T('\0');
1387 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1388 // total number of characters which would have been written if the
1389 // buffer were large enough (newer standards such as Unix98)
1392 #if wxUSE_WXVSNPRINTF
1393 // we know that our own implementation of wxVsnprintf() returns -1
1394 // only for a format error - thus there's something wrong with
1395 // the user's format string
1397 #else // assume that system version only returns error if not enough space
1398 // still not enough, as we don't know how much we need, double the
1399 // current size of the buffer
1401 #endif // wxUSE_WXVSNPRINTF/!wxUSE_WXVSNPRINTF
1403 else if ( len
>= size
)
1405 #if wxUSE_WXVSNPRINTF
1406 // we know that our own implementation of wxVsnprintf() returns
1407 // size+1 when there's not enough space but that's not the size
1408 // of the required buffer!
1409 size
*= 2; // so we just double the current size of the buffer
1411 // some vsnprintf() implementations NUL-terminate the buffer and
1412 // some don't in len == size case, to be safe always add 1
1416 else // ok, there was enough space
1422 // we could have overshot
1428 // ----------------------------------------------------------------------------
1429 // misc other operations
1430 // ----------------------------------------------------------------------------
1432 // returns true if the string matches the pattern which may contain '*' and
1433 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1435 bool wxString::Matches(const wxString
& mask
) const
1437 // I disable this code as it doesn't seem to be faster (in fact, it seems
1438 // to be much slower) than the old, hand-written code below and using it
1439 // here requires always linking with libregex even if the user code doesn't
1441 #if 0 // wxUSE_REGEX
1442 // first translate the shell-like mask into a regex
1444 pattern
.reserve(wxStrlen(pszMask
));
1456 pattern
+= _T(".*");
1467 // these characters are special in a RE, quote them
1468 // (however note that we don't quote '[' and ']' to allow
1469 // using them for Unix shell like matching)
1470 pattern
+= _T('\\');
1474 pattern
+= *pszMask
;
1482 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1483 #else // !wxUSE_REGEX
1484 // TODO: this is, of course, awfully inefficient...
1486 // FIXME-UTF8: implement using iterators, remove #if
1487 #if wxUSE_UNICODE_UTF8
1488 wxWCharBuffer maskBuf
= mask
.wc_str();
1489 wxWCharBuffer txtBuf
= wc_str();
1490 const wxChar
*pszMask
= maskBuf
.data();
1491 const wxChar
*pszTxt
= txtBuf
.data();
1493 const wxChar
*pszMask
= mask
.wx_str();
1494 // the char currently being checked
1495 const wxChar
*pszTxt
= wx_str();
1498 // the last location where '*' matched
1499 const wxChar
*pszLastStarInText
= NULL
;
1500 const wxChar
*pszLastStarInMask
= NULL
;
1503 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1504 switch ( *pszMask
) {
1506 if ( *pszTxt
== wxT('\0') )
1509 // pszTxt and pszMask will be incremented in the loop statement
1515 // remember where we started to be able to backtrack later
1516 pszLastStarInText
= pszTxt
;
1517 pszLastStarInMask
= pszMask
;
1519 // ignore special chars immediately following this one
1520 // (should this be an error?)
1521 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1524 // if there is nothing more, match
1525 if ( *pszMask
== wxT('\0') )
1528 // are there any other metacharacters in the mask?
1530 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1532 if ( pEndMask
!= NULL
) {
1533 // we have to match the string between two metachars
1534 uiLenMask
= pEndMask
- pszMask
;
1537 // we have to match the remainder of the string
1538 uiLenMask
= wxStrlen(pszMask
);
1541 wxString
strToMatch(pszMask
, uiLenMask
);
1542 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1543 if ( pMatch
== NULL
)
1546 // -1 to compensate "++" in the loop
1547 pszTxt
= pMatch
+ uiLenMask
- 1;
1548 pszMask
+= uiLenMask
- 1;
1553 if ( *pszMask
!= *pszTxt
)
1559 // match only if nothing left
1560 if ( *pszTxt
== wxT('\0') )
1563 // if we failed to match, backtrack if we can
1564 if ( pszLastStarInText
) {
1565 pszTxt
= pszLastStarInText
+ 1;
1566 pszMask
= pszLastStarInMask
;
1568 pszLastStarInText
= NULL
;
1570 // don't bother resetting pszLastStarInMask, it's unnecessary
1576 #endif // wxUSE_REGEX/!wxUSE_REGEX
1579 // Count the number of chars
1580 int wxString::Freq(wxUniChar ch
) const
1583 for ( const_iterator i
= begin(); i
!= end(); ++i
)
1591 // convert to upper case, return the copy of the string
1592 wxString
wxString::Upper() const
1593 { wxString
s(*this); return s
.MakeUpper(); }
1595 // convert to lower case, return the copy of the string
1596 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }