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(s
);
135 if ( i
!= hash
.end() )
143 WX_DECLARE_HASH_MAP(wxString
*, char*, wxPointerHash
, wxPointerEqual
,
144 wxStringCharConversionCache
);
145 static wxStringCharConversionCache gs_stringsCharCache
;
147 const char* wxCStrData::AsChar() const
149 // remove previously cache value, if any (see FIXMEs above):
150 DeleteStringFromConversionCache(gs_stringsCharCache
, m_str
);
152 // convert the string and keep it:
153 const char *s
= gs_stringsCharCache
[m_str
] = m_str
->mb_str().release();
157 #endif // wxUSE_UNICODE
159 #if !wxUSE_UNICODE_WCHAR
160 WX_DECLARE_HASH_MAP(wxString
*, wchar_t*, wxPointerHash
, wxPointerEqual
,
161 wxStringWCharConversionCache
);
162 static wxStringWCharConversionCache gs_stringsWCharCache
;
164 const wchar_t* wxCStrData::AsWChar() const
166 // remove previously cache value, if any (see FIXMEs above):
167 DeleteStringFromConversionCache(gs_stringsWCharCache
, m_str
);
169 // convert the string and keep it:
170 const wchar_t *s
= gs_stringsWCharCache
[m_str
] = m_str
->wc_str().release();
174 #endif // !wxUSE_UNICODE_WCHAR
176 // ===========================================================================
177 // wxString class core
178 // ===========================================================================
180 // ---------------------------------------------------------------------------
181 // construction and conversion
182 // ---------------------------------------------------------------------------
184 wxString::~wxString()
187 // FIXME-UTF8: do this only if locale is not UTF8 if wxUSE_UNICODE_UTF8
188 DeleteStringFromConversionCache(gs_stringsCharCache
, this);
190 #if !wxUSE_UNICODE_WCHAR
191 DeleteStringFromConversionCache(gs_stringsWCharCache
, this);
197 wxString::SubstrBufFromMB
wxString::ConvertStr(const char *psz
, size_t nLength
,
198 const wxMBConv
& conv
)
201 if ( !psz
|| nLength
== 0 )
202 return SubstrBufFromMB();
204 if ( nLength
== npos
)
208 wxWCharBuffer
wcBuf(conv
.cMB2WC(psz
, nLength
, &wcLen
));
210 return SubstrBufFromMB();
212 return SubstrBufFromMB(wcBuf
, wcLen
);
216 wxString::SubstrBufFromWC
wxString::ConvertStr(const wchar_t *pwz
, size_t nLength
,
217 const wxMBConv
& conv
)
220 if ( !pwz
|| nLength
== 0 )
221 return SubstrBufFromWC();
223 if ( nLength
== npos
)
227 wxCharBuffer
mbBuf(conv
.cWC2MB(pwz
, nLength
, &mbLen
));
229 return SubstrBufFromWC();
231 return SubstrBufFromWC(mbBuf
, mbLen
);
238 //Convert wxString in Unicode mode to a multi-byte string
239 const wxCharBuffer
wxString::mb_str(const wxMBConv
& conv
) const
241 return conv
.cWC2MB(c_str(), length() + 1 /* size, not length */, NULL
);
248 //Converts this string to a wide character string if unicode
249 //mode is not enabled and wxUSE_WCHAR_T is enabled
250 const wxWCharBuffer
wxString::wc_str(const wxMBConv
& conv
) const
252 return conv
.cMB2WC(c_str(), length() + 1 /* size, not length */, NULL
);
255 #endif // wxUSE_WCHAR_T
257 #endif // Unicode/ANSI
259 // shrink to minimal size (releasing extra memory)
260 bool wxString::Shrink()
262 wxString
tmp(begin(), end());
264 return tmp
.length() == length();
267 // deprecated compatibility code:
268 #if WXWIN_COMPATIBILITY_2_8 && !wxUSE_STL_BASED_WXSTRING && !wxUSE_UNICODE_UTF8
269 wxChar
*wxString::GetWriteBuf(size_t nLen
)
271 return DoGetWriteBuf(nLen
);
274 void wxString::UngetWriteBuf()
279 void wxString::UngetWriteBuf(size_t nLen
)
281 DoUngetWriteBuf(nLen
);
283 #endif // WXWIN_COMPATIBILITY_2_8 && !wxUSE_STL_BASED_WXSTRING && !wxUSE_UNICODE_UTF8
286 // ---------------------------------------------------------------------------
288 // ---------------------------------------------------------------------------
290 // all functions are inline in string.h
292 // ---------------------------------------------------------------------------
293 // concatenation operators
294 // ---------------------------------------------------------------------------
297 * concatenation functions come in 5 flavours:
299 * char + string and string + char
300 * C str + string and string + C str
303 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
305 #if !wxUSE_STL_BASED_WXSTRING
306 wxASSERT( str1
.IsValid() );
307 wxASSERT( str2
.IsValid() );
316 wxString
operator+(const wxString
& str
, wxUniChar ch
)
318 #if !wxUSE_STL_BASED_WXSTRING
319 wxASSERT( str
.IsValid() );
328 wxString
operator+(wxUniChar ch
, const wxString
& str
)
330 #if !wxUSE_STL_BASED_WXSTRING
331 wxASSERT( str
.IsValid() );
340 wxString
operator+(const wxString
& str
, const char *psz
)
342 #if !wxUSE_STL_BASED_WXSTRING
343 wxASSERT( str
.IsValid() );
347 if ( !s
.Alloc(strlen(psz
) + str
.length()) ) {
348 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
356 wxString
operator+(const wxString
& str
, const wchar_t *pwz
)
358 #if !wxUSE_STL_BASED_WXSTRING
359 wxASSERT( str
.IsValid() );
363 if ( !s
.Alloc(wxWcslen(pwz
) + str
.length()) ) {
364 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
372 wxString
operator+(const char *psz
, const wxString
& str
)
374 #if !wxUSE_STL_BASED_WXSTRING
375 wxASSERT( str
.IsValid() );
379 if ( !s
.Alloc(strlen(psz
) + str
.length()) ) {
380 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
388 wxString
operator+(const wchar_t *pwz
, const wxString
& str
)
390 #if !wxUSE_STL_BASED_WXSTRING
391 wxASSERT( str
.IsValid() );
395 if ( !s
.Alloc(wxWcslen(pwz
) + str
.length()) ) {
396 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
404 // ---------------------------------------------------------------------------
406 // ---------------------------------------------------------------------------
408 #ifdef HAVE_STD_STRING_COMPARE
410 // NB: Comparison code (both if HAVE_STD_STRING_COMPARE and if not) works with
411 // UTF-8 encoded strings too, thanks to UTF-8's design which allows us to
412 // sort strings in characters code point order by sorting the byte sequence
413 // in byte values order (i.e. what strcmp() and memcmp() do).
415 int wxString::compare(const wxString
& str
) const
417 return m_impl
.compare(str
.m_impl
);
420 int wxString::compare(size_t nStart
, size_t nLen
,
421 const wxString
& str
) const
424 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
425 return m_impl
.compare(pos
, len
, str
.m_impl
);
428 int wxString::compare(size_t nStart
, size_t nLen
,
430 size_t nStart2
, size_t nLen2
) const
433 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
436 str
.PosLenToImpl(nStart2
, nLen2
, &pos2
, &len2
);
438 return m_impl
.compare(pos
, len
, str
.m_impl
, pos2
, len2
);
441 int wxString::compare(const char* sz
) const
443 return m_impl
.compare(ImplStr(sz
));
446 int wxString::compare(const wchar_t* sz
) const
448 return m_impl
.compare(ImplStr(sz
));
451 int wxString::compare(size_t nStart
, size_t nLen
,
452 const char* sz
, size_t nCount
) const
455 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
457 SubstrBufFromMB
str(ImplStr(sz
, nCount
));
459 return m_impl
.compare(pos
, len
, str
.data
, str
.len
);
462 int wxString::compare(size_t nStart
, size_t nLen
,
463 const wchar_t* sz
, size_t nCount
) const
466 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
468 SubstrBufFromWC
str(ImplStr(sz
, nCount
));
470 return m_impl
.compare(pos
, len
, str
.data
, str
.len
);
473 #else // !HAVE_STD_STRING_COMPARE
475 static inline int wxDoCmp(const wxStringCharType
* s1
, size_t l1
,
476 const wxStringCharType
* s2
, size_t l2
)
479 return wxStringMemcmp(s1
, s2
, l1
);
482 int ret
= wxStringMemcmp(s1
, s2
, l1
);
483 return ret
== 0 ? -1 : ret
;
487 int ret
= wxStringMemcmp(s1
, s2
, l2
);
488 return ret
== 0 ? +1 : ret
;
492 int wxString::compare(const wxString
& str
) const
494 return ::wxDoCmp(m_impl
.data(), m_impl
.length(),
495 str
.m_impl
.data(), str
.m_impl
.length());
498 int wxString::compare(size_t nStart
, size_t nLen
,
499 const wxString
& str
) const
501 wxASSERT(nStart
<= length());
502 size_type strLen
= length() - nStart
;
503 nLen
= strLen
< nLen
? strLen
: nLen
;
506 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
508 return ::wxDoCmp(m_impl
.data() + pos
, len
,
509 str
.m_impl
.data(), str
.m_impl
.length());
512 int wxString::compare(size_t nStart
, size_t nLen
,
514 size_t nStart2
, size_t nLen2
) const
516 wxASSERT(nStart
<= length());
517 wxASSERT(nStart2
<= str
.length());
518 size_type strLen
= length() - nStart
,
519 strLen2
= str
.length() - nStart2
;
520 nLen
= strLen
< nLen
? strLen
: nLen
;
521 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
524 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
526 str
.PosLenToImpl(nStart2
, nLen2
, &pos2
, &len2
);
528 return ::wxDoCmp(m_impl
.data() + pos
, len
,
529 str
.m_impl
.data() + pos2
, len2
);
532 int wxString::compare(const char* sz
) const
534 SubstrBufFromMB
str(ImplStr(sz
, npos
));
535 if ( str
.len
== npos
)
536 str
.len
= wxStringStrlen(str
.data
);
537 return ::wxDoCmp(m_impl
.data(), m_impl
.length(), str
.data
, str
.len
);
540 int wxString::compare(const wchar_t* sz
) const
542 SubstrBufFromWC
str(ImplStr(sz
, npos
));
543 if ( str
.len
== npos
)
544 str
.len
= wxStringStrlen(str
.data
);
545 return ::wxDoCmp(m_impl
.data(), m_impl
.length(), str
.data
, str
.len
);
548 int wxString::compare(size_t nStart
, size_t nLen
,
549 const char* sz
, size_t nCount
) const
551 wxASSERT(nStart
<= length());
552 size_type strLen
= length() - nStart
;
553 nLen
= strLen
< nLen
? strLen
: nLen
;
556 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
558 SubstrBufFromMB
str(ImplStr(sz
, nCount
));
559 if ( str
.len
== npos
)
560 str
.len
= wxStringStrlen(str
.data
);
562 return ::wxDoCmp(m_impl
.data() + pos
, len
, str
.data
, str
.len
);
565 int wxString::compare(size_t nStart
, size_t nLen
,
566 const wchar_t* sz
, size_t nCount
) const
568 wxASSERT(nStart
<= length());
569 size_type strLen
= length() - nStart
;
570 nLen
= strLen
< nLen
? strLen
: nLen
;
573 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
575 SubstrBufFromWC
str(ImplStr(sz
, nCount
));
576 if ( str
.len
== npos
)
577 str
.len
= wxStringStrlen(str
.data
);
579 return ::wxDoCmp(m_impl
.data() + pos
, len
, str
.data
, str
.len
);
582 #endif // HAVE_STD_STRING_COMPARE/!HAVE_STD_STRING_COMPARE
585 // ---------------------------------------------------------------------------
586 // find_{first,last}_[not]_of functions
587 // ---------------------------------------------------------------------------
589 #if !wxUSE_STL_BASED_WXSTRING || wxUSE_UNICODE_UTF8
591 // NB: All these functions are implemented with the argument being wxChar*,
592 // i.e. widechar string in any Unicode build, even though native string
593 // representation is char* in the UTF-8 build. This is because we couldn't
594 // use memchr() to determine if a character is in a set encoded as UTF-8.
596 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
598 return find_first_of(sz
, nStart
, wxStrlen(sz
));
601 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
603 return find_first_not_of(sz
, nStart
, wxStrlen(sz
));
606 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
608 wxASSERT_MSG( nStart
<= length(), _T("invalid index") );
611 for ( const_iterator i
= begin() + nStart
; i
!= end(); ++idx
, ++i
)
613 if ( wxTmemchr(sz
, *i
, n
) )
620 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
622 wxASSERT_MSG( nStart
<= length(), _T("invalid index") );
625 for ( const_iterator i
= begin() + nStart
; i
!= end(); ++idx
, ++i
)
627 if ( !wxTmemchr(sz
, *i
, n
) )
635 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
637 return find_last_of(sz
, nStart
, wxStrlen(sz
));
640 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
642 return find_last_not_of(sz
, nStart
, wxStrlen(sz
));
645 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
647 size_t len
= length();
649 if ( nStart
== npos
)
655 wxASSERT_MSG( nStart
<= len
, _T("invalid index") );
659 for ( const_reverse_iterator i
= rbegin() + (len
- nStart
- 1);
660 i
!= rend(); --idx
, ++i
)
662 if ( wxTmemchr(sz
, *i
, n
) )
669 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
671 size_t len
= length();
673 if ( nStart
== npos
)
679 wxASSERT_MSG( nStart
<= len
, _T("invalid index") );
683 for ( const_reverse_iterator i
= rbegin() + (len
- nStart
- 1);
684 i
!= rend(); --idx
, ++i
)
686 if ( !wxTmemchr(sz
, *i
, n
) )
693 size_t wxString::find_first_not_of(wxUniChar ch
, size_t nStart
) const
695 wxASSERT_MSG( nStart
<= length(), _T("invalid index") );
698 for ( const_iterator i
= begin() + nStart
; i
!= end(); ++idx
, ++i
)
707 size_t wxString::find_last_not_of(wxUniChar ch
, size_t nStart
) const
709 size_t len
= length();
711 if ( nStart
== npos
)
717 wxASSERT_MSG( nStart
<= len
, _T("invalid index") );
721 for ( const_reverse_iterator i
= rbegin() + (len
- nStart
- 1);
722 i
!= rend(); --idx
, ++i
)
731 // the functions above were implemented for wchar_t* arguments in Unicode
732 // build and char* in ANSI build; below are implementations for the other
735 #define wxOtherCharType char
736 #define STRCONV (const wxChar*)wxConvLibc.cMB2WC
738 #define wxOtherCharType wchar_t
739 #define STRCONV (const wxChar*)wxConvLibc.cWC2MB
742 size_t wxString::find_first_of(const wxOtherCharType
* sz
, size_t nStart
) const
743 { return find_first_of(STRCONV(sz
), nStart
); }
745 size_t wxString::find_first_of(const wxOtherCharType
* sz
, size_t nStart
,
747 { return find_first_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
748 size_t wxString::find_last_of(const wxOtherCharType
* sz
, size_t nStart
) const
749 { return find_last_of(STRCONV(sz
), nStart
); }
750 size_t wxString::find_last_of(const wxOtherCharType
* sz
, size_t nStart
,
752 { return find_last_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
753 size_t wxString::find_first_not_of(const wxOtherCharType
* sz
, size_t nStart
) const
754 { return find_first_not_of(STRCONV(sz
), nStart
); }
755 size_t wxString::find_first_not_of(const wxOtherCharType
* sz
, size_t nStart
,
757 { return find_first_not_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
758 size_t wxString::find_last_not_of(const wxOtherCharType
* sz
, size_t nStart
) const
759 { return find_last_not_of(STRCONV(sz
), nStart
); }
760 size_t wxString::find_last_not_of(const wxOtherCharType
* sz
, size_t nStart
,
762 { return find_last_not_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
764 #undef wxOtherCharType
767 #endif // !wxUSE_STL_BASED_WXSTRING || wxUSE_UNICODE_UTF8
769 // ===========================================================================
770 // other common string functions
771 // ===========================================================================
773 int wxString::CmpNoCase(const wxString
& s
) const
775 // FIXME-UTF8: use wxUniChar::ToLower/ToUpper once added
778 const_iterator i1
= begin();
779 const_iterator end1
= end();
780 const_iterator i2
= s
.begin();
781 const_iterator end2
= s
.end();
783 for ( ; i1
!= end1
&& i2
!= end2
; ++idx
, ++i1
, ++i2
)
785 wxUniChar lower1
= (wxChar
)wxTolower(*i1
);
786 wxUniChar lower2
= (wxChar
)wxTolower(*i2
);
787 if ( lower1
!= lower2
)
788 return lower1
< lower2
? -1 : 1;
791 size_t len1
= length();
792 size_t len2
= s
.length();
796 else if ( len1
> len2
)
805 #ifndef __SCHAR_MAX__
806 #define __SCHAR_MAX__ 127
810 wxString
wxString::FromAscii(const char *ascii
)
813 return wxEmptyString
;
815 size_t len
= strlen( ascii
);
820 wxStringBuffer
buf(res
, len
);
826 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
834 wxString
wxString::FromAscii(const char ascii
)
836 // What do we do with '\0' ?
839 res
+= (wchar_t)(unsigned char) ascii
;
844 const wxCharBuffer
wxString::ToAscii() const
846 // this will allocate enough space for the terminating NUL too
847 wxCharBuffer
buffer(length());
850 char *dest
= buffer
.data();
852 const wchar_t *pwc
= c_str();
855 *dest
++ = (char)(*pwc
> SCHAR_MAX
? wxT('_') : *pwc
);
857 // the output string can't have embedded NULs anyhow, so we can safely
858 // stop at first of them even if we do have any
868 // extract string of length nCount starting at nFirst
869 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
871 size_t nLen
= length();
873 // default value of nCount is npos and means "till the end"
874 if ( nCount
== npos
)
876 nCount
= nLen
- nFirst
;
879 // out-of-bounds requests return sensible things
880 if ( nFirst
+ nCount
> nLen
)
882 nCount
= nLen
- nFirst
;
887 // AllocCopy() will return empty string
888 return wxEmptyString
;
891 wxString
dest(*this, nFirst
, nCount
);
892 if ( dest
.length() != nCount
)
894 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
900 // check that the string starts with prefix and return the rest of the string
901 // in the provided pointer if it is not NULL, otherwise return false
902 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
904 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
906 // first check if the beginning of the string matches the prefix: note
907 // that we don't have to check that we don't run out of this string as
908 // when we reach the terminating NUL, either prefix string ends too (and
909 // then it's ok) or we break out of the loop because there is no match
910 const wxChar
*p
= c_str();
913 if ( *prefix
++ != *p
++ )
922 // put the rest of the string into provided pointer
930 // check that the string ends with suffix and return the rest of it in the
931 // provided pointer if it is not NULL, otherwise return false
932 bool wxString::EndsWith(const wxChar
*suffix
, wxString
*rest
) const
934 wxASSERT_MSG( suffix
, _T("invalid parameter in wxString::EndssWith") );
936 int start
= length() - wxStrlen(suffix
);
937 if ( start
< 0 || wxStrcmp(wx_str() + start
, suffix
) != 0 )
942 // put the rest of the string into provided pointer
943 rest
->assign(*this, 0, start
);
950 // extract nCount last (rightmost) characters
951 wxString
wxString::Right(size_t nCount
) const
953 if ( nCount
> length() )
956 wxString
dest(*this, length() - nCount
, nCount
);
957 if ( dest
.length() != nCount
) {
958 wxFAIL_MSG( _T("out of memory in wxString::Right") );
963 // get all characters after the last occurence of ch
964 // (returns the whole string if ch not found)
965 wxString
wxString::AfterLast(wxUniChar ch
) const
968 int iPos
= Find(ch
, true);
969 if ( iPos
== wxNOT_FOUND
)
972 str
= wx_str() + iPos
+ 1;
977 // extract nCount first (leftmost) characters
978 wxString
wxString::Left(size_t nCount
) const
980 if ( nCount
> length() )
983 wxString
dest(*this, 0, nCount
);
984 if ( dest
.length() != nCount
) {
985 wxFAIL_MSG( _T("out of memory in wxString::Left") );
990 // get all characters before the first occurence of ch
991 // (returns the whole string if ch not found)
992 wxString
wxString::BeforeFirst(wxUniChar ch
) const
995 if ( iPos
== wxNOT_FOUND
) iPos
= length();
996 return wxString(*this, 0, iPos
);
999 /// get all characters before the last occurence of ch
1000 /// (returns empty string if ch not found)
1001 wxString
wxString::BeforeLast(wxUniChar ch
) const
1004 int iPos
= Find(ch
, true);
1005 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1006 str
= wxString(c_str(), iPos
);
1011 /// get all characters after the first occurence of ch
1012 /// (returns empty string if ch not found)
1013 wxString
wxString::AfterFirst(wxUniChar ch
) const
1016 int iPos
= Find(ch
);
1017 if ( iPos
!= wxNOT_FOUND
)
1018 str
= wx_str() + iPos
+ 1;
1023 // replace first (or all) occurences of some substring with another one
1024 size_t wxString::Replace(const wxString
& strOld
,
1025 const wxString
& strNew
, bool bReplaceAll
)
1027 // if we tried to replace an empty string we'd enter an infinite loop below
1028 wxCHECK_MSG( !strOld
.empty(), 0,
1029 _T("wxString::Replace(): invalid parameter") );
1031 size_t uiCount
= 0; // count of replacements made
1033 size_t uiOldLen
= strOld
.length();
1034 size_t uiNewLen
= strNew
.length();
1038 while ( (*this)[dwPos
] != wxT('\0') )
1040 //DO NOT USE STRSTR HERE
1041 //this string can contain embedded null characters,
1042 //so strstr will function incorrectly
1043 dwPos
= find(strOld
, dwPos
);
1044 if ( dwPos
== npos
)
1045 break; // exit the loop
1048 //replace this occurance of the old string with the new one
1049 replace(dwPos
, uiOldLen
, strNew
, uiNewLen
);
1051 //move up pos past the string that was replaced
1054 //increase replace count
1059 break; // exit the loop
1066 bool wxString::IsAscii() const
1068 const wxChar
*s
= (const wxChar
*) *this;
1070 if(!isascii(*s
)) return(false);
1076 bool wxString::IsWord() const
1078 const wxChar
*s
= (const wxChar
*) *this;
1080 if(!wxIsalpha(*s
)) return(false);
1086 bool wxString::IsNumber() const
1088 const wxChar
*s
= (const wxChar
*) *this;
1090 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1092 if(!wxIsdigit(*s
)) return(false);
1098 wxString
wxString::Strip(stripType w
) const
1101 if ( w
& leading
) s
.Trim(false);
1102 if ( w
& trailing
) s
.Trim(true);
1106 // ---------------------------------------------------------------------------
1108 // ---------------------------------------------------------------------------
1110 wxString
& wxString::MakeUpper()
1112 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1113 *it
= (wxChar
)wxToupper(*it
);
1118 wxString
& wxString::MakeLower()
1120 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1121 *it
= (wxChar
)wxTolower(*it
);
1126 // ---------------------------------------------------------------------------
1127 // trimming and padding
1128 // ---------------------------------------------------------------------------
1130 // some compilers (VC++ 6.0 not to name them) return true for a call to
1131 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1132 // live with this by checking that the character is a 7 bit one - even if this
1133 // may fail to detect some spaces (I don't know if Unicode doesn't have
1134 // space-like symbols somewhere except in the first 128 chars), it is arguably
1135 // still better than trimming away accented letters
1136 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1138 // trims spaces (in the sense of isspace) from left or right side
1139 wxString
& wxString::Trim(bool bFromRight
)
1141 // first check if we're going to modify the string at all
1144 (bFromRight
&& wxSafeIsspace(GetChar(length() - 1))) ||
1145 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1151 // find last non-space character
1152 reverse_iterator psz
= rbegin();
1153 while ( (psz
!= rend()) && wxSafeIsspace(*psz
) )
1156 // truncate at trailing space start
1157 erase(psz
.base(), end());
1161 // find first non-space character
1162 iterator psz
= begin();
1163 while ( (psz
!= end()) && wxSafeIsspace(*psz
) )
1166 // fix up data and length
1167 erase(begin(), psz
);
1174 // adds nCount characters chPad to the string from either side
1175 wxString
& wxString::Pad(size_t nCount
, wxUniChar chPad
, bool bFromRight
)
1177 wxString
s(chPad
, nCount
);
1190 // truncate the string
1191 wxString
& wxString::Truncate(size_t uiLen
)
1193 if ( uiLen
< length() )
1195 erase(begin() + uiLen
, end());
1197 //else: nothing to do, string is already short enough
1202 // ---------------------------------------------------------------------------
1203 // finding (return wxNOT_FOUND if not found and index otherwise)
1204 // ---------------------------------------------------------------------------
1207 int wxString::Find(wxUniChar ch
, bool bFromEnd
) const
1209 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1211 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1214 // ----------------------------------------------------------------------------
1215 // conversion to numbers
1216 // ----------------------------------------------------------------------------
1218 // the implementation of all the functions below is exactly the same so factor
1221 template <typename T
, typename F
>
1222 bool wxStringToIntType(const wxChar
*start
,
1227 wxCHECK_MSG( val
, false, _T("NULL output pointer") );
1228 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1235 *val
= (*func
)(start
, &end
, base
);
1237 // return true only if scan was stopped by the terminating NUL and if the
1238 // string was not empty to start with and no under/overflow occurred
1239 return !*end
&& (end
!= start
)
1241 && (errno
!= ERANGE
)
1246 bool wxString::ToLong(long *val
, int base
) const
1248 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtol
);
1251 bool wxString::ToULong(unsigned long *val
, int base
) const
1253 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtoul
);
1256 bool wxString::ToLongLong(wxLongLong_t
*val
, int base
) const
1258 #ifdef wxHAS_STRTOLL
1259 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtoll
);
1261 // TODO: implement this ourselves
1265 #endif // wxHAS_STRTOLL
1268 bool wxString::ToULongLong(wxULongLong_t
*val
, int base
) const
1270 #ifdef wxHAS_STRTOLL
1271 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtoull
);
1273 // TODO: implement this ourselves
1280 bool wxString::ToDouble(double *val
) const
1282 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1288 const wxChar
*start
= c_str();
1290 *val
= wxStrtod(start
, &end
);
1292 // return true only if scan was stopped by the terminating NUL and if the
1293 // string was not empty to start with and no under/overflow occurred
1294 return !*end
&& (end
!= start
)
1296 && (errno
!= ERANGE
)
1301 // ---------------------------------------------------------------------------
1303 // ---------------------------------------------------------------------------
1306 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1307 wxString
wxStringPrintfMixinBase::DoFormat(const wxChar
*format
, ...)
1309 wxString
wxString::DoFormat(const wxChar
*format
, ...)
1313 va_start(argptr
, format
);
1316 s
.PrintfV(format
, argptr
);
1324 wxString
wxString::FormatV(const wxString
& format
, va_list argptr
)
1327 s
.PrintfV(format
, argptr
);
1331 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1332 int wxStringPrintfMixinBase::DoPrintf(const wxChar
*format
, ...)
1334 int wxString::DoPrintf(const wxChar
*format
, ...)
1338 va_start(argptr
, format
);
1340 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1341 // get a pointer to the wxString instance; we have to use dynamic_cast<>
1342 // because it's the only cast that works safely for downcasting when
1343 // multiple inheritance is used:
1344 wxString
*str
= static_cast<wxString
*>(this);
1346 wxString
*str
= this;
1349 int iLen
= str
->PrintfV(format
, argptr
);
1356 int wxString::PrintfV(const wxString
& format
, va_list argptr
)
1362 wxStringBuffer
tmp(*this, size
+ 1);
1371 // wxVsnprintf() may modify the original arg pointer, so pass it
1374 wxVaCopy(argptrcopy
, argptr
);
1375 int len
= wxVsnprintf(buf
, size
, format
, argptrcopy
);
1378 // some implementations of vsnprintf() don't NUL terminate
1379 // the string if there is not enough space for it so
1380 // always do it manually
1381 buf
[size
] = _T('\0');
1383 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1384 // total number of characters which would have been written if the
1385 // buffer were large enough (newer standards such as Unix98)
1388 #if wxUSE_WXVSNPRINTF
1389 // we know that our own implementation of wxVsnprintf() returns -1
1390 // only for a format error - thus there's something wrong with
1391 // the user's format string
1393 #else // assume that system version only returns error if not enough space
1394 // still not enough, as we don't know how much we need, double the
1395 // current size of the buffer
1397 #endif // wxUSE_WXVSNPRINTF/!wxUSE_WXVSNPRINTF
1399 else if ( len
>= size
)
1401 #if wxUSE_WXVSNPRINTF
1402 // we know that our own implementation of wxVsnprintf() returns
1403 // size+1 when there's not enough space but that's not the size
1404 // of the required buffer!
1405 size
*= 2; // so we just double the current size of the buffer
1407 // some vsnprintf() implementations NUL-terminate the buffer and
1408 // some don't in len == size case, to be safe always add 1
1412 else // ok, there was enough space
1418 // we could have overshot
1424 // ----------------------------------------------------------------------------
1425 // misc other operations
1426 // ----------------------------------------------------------------------------
1428 // returns true if the string matches the pattern which may contain '*' and
1429 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1431 bool wxString::Matches(const wxString
& mask
) const
1433 // I disable this code as it doesn't seem to be faster (in fact, it seems
1434 // to be much slower) than the old, hand-written code below and using it
1435 // here requires always linking with libregex even if the user code doesn't
1437 #if 0 // wxUSE_REGEX
1438 // first translate the shell-like mask into a regex
1440 pattern
.reserve(wxStrlen(pszMask
));
1452 pattern
+= _T(".*");
1463 // these characters are special in a RE, quote them
1464 // (however note that we don't quote '[' and ']' to allow
1465 // using them for Unix shell like matching)
1466 pattern
+= _T('\\');
1470 pattern
+= *pszMask
;
1478 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1479 #else // !wxUSE_REGEX
1480 // TODO: this is, of course, awfully inefficient...
1482 // FIXME-UTF8: implement using iterators, remove #if
1483 #if wxUSE_UNICODE_UTF8
1484 wxWCharBuffer maskBuf
= mask
.wc_str();
1485 wxWCharBuffer txtBuf
= wc_str();
1486 const wxChar
*pszMask
= maskBuf
.data();
1487 const wxChar
*pszTxt
= txtBuf
.data();
1489 const wxChar
*pszMask
= mask
.wx_str();
1490 // the char currently being checked
1491 const wxChar
*pszTxt
= wx_str();
1494 // the last location where '*' matched
1495 const wxChar
*pszLastStarInText
= NULL
;
1496 const wxChar
*pszLastStarInMask
= NULL
;
1499 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1500 switch ( *pszMask
) {
1502 if ( *pszTxt
== wxT('\0') )
1505 // pszTxt and pszMask will be incremented in the loop statement
1511 // remember where we started to be able to backtrack later
1512 pszLastStarInText
= pszTxt
;
1513 pszLastStarInMask
= pszMask
;
1515 // ignore special chars immediately following this one
1516 // (should this be an error?)
1517 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1520 // if there is nothing more, match
1521 if ( *pszMask
== wxT('\0') )
1524 // are there any other metacharacters in the mask?
1526 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1528 if ( pEndMask
!= NULL
) {
1529 // we have to match the string between two metachars
1530 uiLenMask
= pEndMask
- pszMask
;
1533 // we have to match the remainder of the string
1534 uiLenMask
= wxStrlen(pszMask
);
1537 wxString
strToMatch(pszMask
, uiLenMask
);
1538 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1539 if ( pMatch
== NULL
)
1542 // -1 to compensate "++" in the loop
1543 pszTxt
= pMatch
+ uiLenMask
- 1;
1544 pszMask
+= uiLenMask
- 1;
1549 if ( *pszMask
!= *pszTxt
)
1555 // match only if nothing left
1556 if ( *pszTxt
== wxT('\0') )
1559 // if we failed to match, backtrack if we can
1560 if ( pszLastStarInText
) {
1561 pszTxt
= pszLastStarInText
+ 1;
1562 pszMask
= pszLastStarInMask
;
1564 pszLastStarInText
= NULL
;
1566 // don't bother resetting pszLastStarInMask, it's unnecessary
1572 #endif // wxUSE_REGEX/!wxUSE_REGEX
1575 // Count the number of chars
1576 int wxString::Freq(wxUniChar ch
) const
1579 for ( const_iterator i
= begin(); i
!= end(); ++i
)
1587 // convert to upper case, return the copy of the string
1588 wxString
wxString::Upper() const
1589 { wxString
s(*this); return s
.MakeUpper(); }
1591 // convert to lower case, return the copy of the string
1592 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }