1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "string.h"
18 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
19 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
20 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
23 // ===========================================================================
24 // headers, declarations, constants
25 // ===========================================================================
27 // For compilers that support precompilation, includes "wx.h".
28 #include "wx/wxprec.h"
36 #include "wx/string.h"
49 #include <wchar.h> // for wcsrtombs(), see comments where it's used
52 #ifdef WXSTRING_IS_WXOBJECT
53 IMPLEMENT_DYNAMIC_CLASS(wxString
, wxObject
)
54 #endif //WXSTRING_IS_WXOBJECT
56 // allocating extra space for each string consumes more memory but speeds up
57 // the concatenation operations (nLen is the current string's length)
58 // NB: EXTRA_ALLOC must be >= 0!
59 #define EXTRA_ALLOC (19 - nLen % 16)
61 // ---------------------------------------------------------------------------
62 // static class variables definition
63 // ---------------------------------------------------------------------------
65 #ifdef wxSTD_STRING_COMPATIBILITY
66 const size_t wxString::npos
= wxSTRING_MAXLEN
;
67 #endif // wxSTD_STRING_COMPATIBILITY
69 // ----------------------------------------------------------------------------
71 // ----------------------------------------------------------------------------
73 // for an empty string, GetStringData() will return this address: this
74 // structure has the same layout as wxStringData and it's data() method will
75 // return the empty string (dummy pointer)
80 } g_strEmpty
= { {-1, 0, 0}, '\0' };
82 // empty C style string: points to 'string data' byte of g_strEmpty
83 extern const char WXDLLEXPORT
*g_szNul
= &g_strEmpty
.dummy
;
85 // ----------------------------------------------------------------------------
86 // conditional compilation
87 // ----------------------------------------------------------------------------
89 // we want to find out if the current platform supports vsnprintf()-like
90 // function: for Unix this is done with configure, for Windows we test the
91 // compiler explicitly.
94 #define wxVsprintf _vsnprintf
98 #define wxVsprintf vsnprintf
100 #endif // Windows/!Windows
103 // in this case we'll use vsprintf() (which is ANSI and thus should be
104 // always available), but it's unsafe because it doesn't check for buffer
105 // size - so give a warning
106 #define wxVsprintf(buffer,len,format,argptr) vsprintf(buffer,format, argptr)
108 #if defined(__VISUALC__)
109 #pragma message("Using sprintf() because no snprintf()-like function defined")
110 #elif defined(__GNUG__) && !defined(__UNIX__)
111 #warning "Using sprintf() because no snprintf()-like function defined"
112 #elif defined(__MWERKS__)
113 #warning "Using sprintf() because no snprintf()-like function defined"
115 #endif // no vsnprintf
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 #ifdef wxSTD_STRING_COMPATIBILITY
123 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
126 // ATTN: you can _not_ use both of these in the same program!
128 istream
& operator>>(istream
& is
, wxString
& WXUNUSED(str
))
133 streambuf
*sb
= is
.rdbuf();
136 int ch
= sb
->sbumpc ();
138 is
.setstate(ios::eofbit
);
141 else if ( isspace(ch
) ) {
153 if ( str
.length() == 0 )
154 is
.setstate(ios::failbit
);
159 #endif //std::string compatibility
161 // ----------------------------------------------------------------------------
163 // ----------------------------------------------------------------------------
165 // this small class is used to gather statistics for performance tuning
166 //#define WXSTRING_STATISTICS
167 #ifdef WXSTRING_STATISTICS
171 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
173 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
175 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
178 size_t m_nCount
, m_nTotal
;
180 } g_averageLength("allocation size"),
181 g_averageSummandLength("summand length"),
182 g_averageConcatHit("hit probability in concat"),
183 g_averageInitialLength("initial string length");
185 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
187 #define STATISTICS_ADD(av, val)
188 #endif // WXSTRING_STATISTICS
190 // ===========================================================================
191 // wxString class core
192 // ===========================================================================
194 // ---------------------------------------------------------------------------
196 // ---------------------------------------------------------------------------
198 // constructs string of <nLength> copies of character <ch>
199 wxString::wxString(char ch
, size_t nLength
)
204 AllocBuffer(nLength
);
206 wxASSERT( sizeof(char) == 1 ); // can't use memset if not
208 memset(m_pchData
, ch
, nLength
);
212 // takes nLength elements of psz starting at nPos
213 void wxString::InitWith(const char *psz
, size_t nPos
, size_t nLength
)
217 wxASSERT( nPos
<= Strlen(psz
) );
219 if ( nLength
== wxSTRING_MAXLEN
)
220 nLength
= Strlen(psz
+ nPos
);
222 STATISTICS_ADD(InitialLength
, nLength
);
225 // trailing '\0' is written in AllocBuffer()
226 AllocBuffer(nLength
);
227 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(char));
231 // the same as previous constructor, but for compilers using unsigned char
232 wxString::wxString(const unsigned char* psz
, size_t nLength
)
234 InitWith((const char *)psz
, 0, nLength
);
237 #ifdef wxSTD_STRING_COMPATIBILITY
239 // poor man's iterators are "void *" pointers
240 wxString::wxString(const void *pStart
, const void *pEnd
)
242 InitWith((const char *)pStart
, 0,
243 (const char *)pEnd
- (const char *)pStart
);
246 #endif //std::string compatibility
249 wxString::wxString(const wchar_t *pwz
)
251 // first get necessary size
253 // NB: GNU libc5 wcstombs() is completely broken, don't use it (it doesn't
254 // honor the 3rd parameter, thus it will happily crash here).
256 // don't know if it's really needed (or if we can pass NULL), but better safe
259 size_t nLen
= wcsrtombs((char *) NULL
, &pwz
, 0, &mbstate
);
261 size_t nLen
= wcstombs((char *) NULL
, pwz
, 0);
267 wcstombs(m_pchData
, pwz
, nLen
);
274 // ---------------------------------------------------------------------------
276 // ---------------------------------------------------------------------------
278 // allocates memory needed to store a C string of length nLen
279 void wxString::AllocBuffer(size_t nLen
)
281 wxASSERT( nLen
> 0 ); //
282 wxASSERT( nLen
<= INT_MAX
-1 ); // max size (enough room for 1 extra)
284 STATISTICS_ADD(Length
, nLen
);
287 // 1) one extra character for '\0' termination
288 // 2) sizeof(wxStringData) for housekeeping info
289 wxStringData
* pData
= (wxStringData
*)
290 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(char));
292 pData
->nDataLength
= nLen
;
293 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
294 m_pchData
= pData
->data(); // data starts after wxStringData
295 m_pchData
[nLen
] = '\0';
298 // must be called before changing this string
299 void wxString::CopyBeforeWrite()
301 wxStringData
* pData
= GetStringData();
303 if ( pData
->IsShared() ) {
304 pData
->Unlock(); // memory not freed because shared
305 size_t nLen
= pData
->nDataLength
;
307 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(char));
310 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
313 // must be called before replacing contents of this string
314 void wxString::AllocBeforeWrite(size_t nLen
)
316 wxASSERT( nLen
!= 0 ); // doesn't make any sense
318 // must not share string and must have enough space
319 wxStringData
* pData
= GetStringData();
320 if ( pData
->IsShared() || (nLen
> pData
->nAllocLength
) ) {
321 // can't work with old buffer, get new one
326 // update the string length
327 pData
->nDataLength
= nLen
;
330 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
333 // allocate enough memory for nLen characters
334 void wxString::Alloc(size_t nLen
)
336 wxStringData
*pData
= GetStringData();
337 if ( pData
->nAllocLength
<= nLen
) {
338 if ( pData
->IsEmpty() ) {
341 wxStringData
* pData
= (wxStringData
*)
342 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(char));
344 pData
->nDataLength
= 0;
345 pData
->nAllocLength
= nLen
;
346 m_pchData
= pData
->data(); // data starts after wxStringData
347 m_pchData
[0u] = '\0';
349 else if ( pData
->IsShared() ) {
350 pData
->Unlock(); // memory not freed because shared
351 size_t nOldLen
= pData
->nDataLength
;
353 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(char));
358 wxStringData
*p
= (wxStringData
*)
359 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(char));
362 // @@@ what to do on memory error?
366 // it's not important if the pointer changed or not (the check for this
367 // is not faster than assigning to m_pchData in all cases)
368 p
->nAllocLength
= nLen
;
369 m_pchData
= p
->data();
372 //else: we've already got enough
375 // shrink to minimal size (releasing extra memory)
376 void wxString::Shrink()
378 wxStringData
*pData
= GetStringData();
380 // this variable is unused in release build, so avoid the compiler warning by
381 // just not declaring it
385 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(char));
387 wxASSERT( p
!= NULL
); // can't free memory?
388 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
391 // get the pointer to writable buffer of (at least) nLen bytes
392 char *wxString::GetWriteBuf(size_t nLen
)
394 AllocBeforeWrite(nLen
);
396 wxASSERT( GetStringData()->nRefs
== 1 );
397 GetStringData()->Validate(FALSE
);
402 // put string back in a reasonable state after GetWriteBuf
403 void wxString::UngetWriteBuf()
405 GetStringData()->nDataLength
= strlen(m_pchData
);
406 GetStringData()->Validate(TRUE
);
409 // ---------------------------------------------------------------------------
411 // ---------------------------------------------------------------------------
413 // all functions are inline in string.h
415 // ---------------------------------------------------------------------------
416 // assignment operators
417 // ---------------------------------------------------------------------------
419 // helper function: does real copy
420 void wxString::AssignCopy(size_t nSrcLen
, const char *pszSrcData
)
422 if ( nSrcLen
== 0 ) {
426 AllocBeforeWrite(nSrcLen
);
427 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(char));
428 GetStringData()->nDataLength
= nSrcLen
;
429 m_pchData
[nSrcLen
] = '\0';
433 // assigns one string to another
434 wxString
& wxString::operator=(const wxString
& stringSrc
)
436 wxASSERT( stringSrc
.GetStringData()->IsValid() );
438 // don't copy string over itself
439 if ( m_pchData
!= stringSrc
.m_pchData
) {
440 if ( stringSrc
.GetStringData()->IsEmpty() ) {
445 GetStringData()->Unlock();
446 m_pchData
= stringSrc
.m_pchData
;
447 GetStringData()->Lock();
454 // assigns a single character
455 wxString
& wxString::operator=(char ch
)
462 wxString
& wxString::operator=(const char *psz
)
464 AssignCopy(Strlen(psz
), psz
);
468 // same as 'signed char' variant
469 wxString
& wxString::operator=(const unsigned char* psz
)
471 *this = (const char *)psz
;
475 wxString
& wxString::operator=(const wchar_t *pwz
)
482 // ---------------------------------------------------------------------------
483 // string concatenation
484 // ---------------------------------------------------------------------------
486 // add something to this string
487 void wxString::ConcatSelf(int nSrcLen
, const char *pszSrcData
)
489 STATISTICS_ADD(SummandLength
, nSrcLen
);
491 // concatenating an empty string is a NOP
493 wxStringData
*pData
= GetStringData();
494 size_t nLen
= pData
->nDataLength
;
495 size_t nNewLen
= nLen
+ nSrcLen
;
497 // alloc new buffer if current is too small
498 if ( pData
->IsShared() ) {
499 STATISTICS_ADD(ConcatHit
, 0);
501 // we have to allocate another buffer
502 wxStringData
* pOldData
= GetStringData();
503 AllocBuffer(nNewLen
);
504 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(char));
507 else if ( nNewLen
> pData
->nAllocLength
) {
508 STATISTICS_ADD(ConcatHit
, 0);
510 // we have to grow the buffer
514 STATISTICS_ADD(ConcatHit
, 1);
516 // the buffer is already big enough
519 // should be enough space
520 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
522 // fast concatenation - all is done in our buffer
523 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(char));
525 m_pchData
[nNewLen
] = '\0'; // put terminating '\0'
526 GetStringData()->nDataLength
= nNewLen
; // and fix the length
528 //else: the string to append was empty
532 * concatenation functions come in 5 flavours:
534 * char + string and string + char
535 * C str + string and string + C str
538 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
540 wxASSERT( string1
.GetStringData()->IsValid() );
541 wxASSERT( string2
.GetStringData()->IsValid() );
543 wxString s
= string1
;
549 wxString
operator+(const wxString
& string
, char ch
)
551 wxASSERT( string
.GetStringData()->IsValid() );
559 wxString
operator+(char ch
, const wxString
& string
)
561 wxASSERT( string
.GetStringData()->IsValid() );
569 wxString
operator+(const wxString
& string
, const char *psz
)
571 wxASSERT( string
.GetStringData()->IsValid() );
574 s
.Alloc(Strlen(psz
) + string
.Len());
581 wxString
operator+(const char *psz
, const wxString
& string
)
583 wxASSERT( string
.GetStringData()->IsValid() );
586 s
.Alloc(Strlen(psz
) + string
.Len());
593 // ===========================================================================
594 // other common string functions
595 // ===========================================================================
597 // ---------------------------------------------------------------------------
598 // simple sub-string extraction
599 // ---------------------------------------------------------------------------
601 // helper function: clone the data attached to this string
602 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
604 if ( nCopyLen
== 0 ) {
608 dest
.AllocBuffer(nCopyLen
);
609 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(char));
613 // extract string of length nCount starting at nFirst
614 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
616 wxStringData
*pData
= GetStringData();
617 size_t nLen
= pData
->nDataLength
;
619 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
620 if ( nCount
== wxSTRING_MAXLEN
)
622 nCount
= nLen
- nFirst
;
625 // out-of-bounds requests return sensible things
626 if ( nFirst
+ nCount
> nLen
)
628 nCount
= nLen
- nFirst
;
633 // AllocCopy() will return empty string
638 AllocCopy(dest
, nCount
, nFirst
);
643 // extract nCount last (rightmost) characters
644 wxString
wxString::Right(size_t nCount
) const
646 if ( nCount
> (size_t)GetStringData()->nDataLength
)
647 nCount
= GetStringData()->nDataLength
;
650 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
654 // get all characters after the last occurence of ch
655 // (returns the whole string if ch not found)
656 wxString
wxString::AfterLast(char ch
) const
659 int iPos
= Find(ch
, TRUE
);
660 if ( iPos
== wxNOT_FOUND
)
663 str
= c_str() + iPos
+ 1;
668 // extract nCount first (leftmost) characters
669 wxString
wxString::Left(size_t nCount
) const
671 if ( nCount
> (size_t)GetStringData()->nDataLength
)
672 nCount
= GetStringData()->nDataLength
;
675 AllocCopy(dest
, nCount
, 0);
679 // get all characters before the first occurence of ch
680 // (returns the whole string if ch not found)
681 wxString
wxString::BeforeFirst(char ch
) const
684 for ( const char *pc
= m_pchData
; *pc
!= '\0' && *pc
!= ch
; pc
++ )
690 /// get all characters before the last occurence of ch
691 /// (returns empty string if ch not found)
692 wxString
wxString::BeforeLast(char ch
) const
695 int iPos
= Find(ch
, TRUE
);
696 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
697 str
= wxString(c_str(), iPos
);
702 /// get all characters after the first occurence of ch
703 /// (returns empty string if ch not found)
704 wxString
wxString::AfterFirst(char ch
) const
708 if ( iPos
!= wxNOT_FOUND
)
709 str
= c_str() + iPos
+ 1;
714 // replace first (or all) occurences of some substring with another one
715 size_t wxString::Replace(const char *szOld
, const char *szNew
, bool bReplaceAll
)
717 size_t uiCount
= 0; // count of replacements made
719 size_t uiOldLen
= Strlen(szOld
);
722 const char *pCurrent
= m_pchData
;
724 while ( *pCurrent
!= '\0' ) {
725 pSubstr
= strstr(pCurrent
, szOld
);
726 if ( pSubstr
== NULL
) {
727 // strTemp is unused if no replacements were made, so avoid the copy
731 strTemp
+= pCurrent
; // copy the rest
732 break; // exit the loop
735 // take chars before match
736 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
738 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
743 if ( !bReplaceAll
) {
744 strTemp
+= pCurrent
; // copy the rest
745 break; // exit the loop
750 // only done if there were replacements, otherwise would have returned above
756 bool wxString::IsAscii() const
758 const char *s
= (const char*) *this;
760 if(!isascii(*s
)) return(FALSE
);
766 bool wxString::IsWord() const
768 const char *s
= (const char*) *this;
770 if(!isalpha(*s
)) return(FALSE
);
776 bool wxString::IsNumber() const
778 const char *s
= (const char*) *this;
780 if(!isdigit(*s
)) return(FALSE
);
786 wxString
wxString::Strip(stripType w
) const
789 if ( w
& leading
) s
.Trim(FALSE
);
790 if ( w
& trailing
) s
.Trim(TRUE
);
794 // ---------------------------------------------------------------------------
796 // ---------------------------------------------------------------------------
798 wxString
& wxString::MakeUpper()
802 for ( char *p
= m_pchData
; *p
; p
++ )
803 *p
= (char)toupper(*p
);
808 wxString
& wxString::MakeLower()
812 for ( char *p
= m_pchData
; *p
; p
++ )
813 *p
= (char)tolower(*p
);
818 // ---------------------------------------------------------------------------
819 // trimming and padding
820 // ---------------------------------------------------------------------------
822 // trims spaces (in the sense of isspace) from left or right side
823 wxString
& wxString::Trim(bool bFromRight
)
825 // first check if we're going to modify the string at all
828 (bFromRight
&& isspace(GetChar(Len() - 1))) ||
829 (!bFromRight
&& isspace(GetChar(0u)))
833 // ok, there is at least one space to trim
838 // find last non-space character
839 char *psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
840 while ( isspace(*psz
) && (psz
>= m_pchData
) )
843 // truncate at trailing space start
845 GetStringData()->nDataLength
= psz
- m_pchData
;
849 // find first non-space character
850 const char *psz
= m_pchData
;
851 while ( isspace(*psz
) )
854 // fix up data and length
855 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const char*) m_pchData
);
856 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(char));
857 GetStringData()->nDataLength
= nDataLength
;
864 // adds nCount characters chPad to the string from either side
865 wxString
& wxString::Pad(size_t nCount
, char chPad
, bool bFromRight
)
867 wxString
s(chPad
, nCount
);
880 // truncate the string
881 wxString
& wxString::Truncate(size_t uiLen
)
883 if ( uiLen
< Len() ) {
886 *(m_pchData
+ uiLen
) = '\0';
887 GetStringData()->nDataLength
= uiLen
;
889 //else: nothing to do, string is already short enough
894 // ---------------------------------------------------------------------------
895 // finding (return wxNOT_FOUND if not found and index otherwise)
896 // ---------------------------------------------------------------------------
899 int wxString::Find(char ch
, bool bFromEnd
) const
901 const char *psz
= bFromEnd
? strrchr(m_pchData
, ch
) : strchr(m_pchData
, ch
);
903 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const char*) m_pchData
;
906 // find a sub-string (like strstr)
907 int wxString::Find(const char *pszSub
) const
909 const char *psz
= strstr(m_pchData
, pszSub
);
911 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const char*) m_pchData
;
914 // ---------------------------------------------------------------------------
915 // stream-like operators
916 // ---------------------------------------------------------------------------
917 wxString
& wxString::operator<<(int i
)
922 return (*this) << res
;
925 wxString
& wxString::operator<<(float f
)
930 return (*this) << res
;
933 wxString
& wxString::operator<<(double d
)
938 return (*this) << res
;
941 // ---------------------------------------------------------------------------
943 // ---------------------------------------------------------------------------
944 int wxString::Printf(const char *pszFormat
, ...)
947 va_start(argptr
, pszFormat
);
949 int iLen
= PrintfV(pszFormat
, argptr
);
956 int wxString::PrintfV(const char* pszFormat
, va_list argptr
)
958 // static buffer to avoid dynamic memory allocation each time
959 static char s_szScratch
[1024];
961 // NB: wxVsprintf() may return either less than the buffer size or -1 if there
962 // is not enough place depending on implementation
963 int iLen
= wxVsprintf(s_szScratch
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
965 if ( iLen
< (int)WXSIZEOF(s_szScratch
) ) {
966 buffer
= s_szScratch
;
969 int size
= WXSIZEOF(s_szScratch
) * 2;
970 buffer
= (char *)malloc(size
);
971 while ( buffer
!= NULL
) {
972 iLen
= wxVsprintf(buffer
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
974 // ok, there was enough space
978 // still not enough, double it again
979 buffer
= (char *)realloc(buffer
, size
*= 2);
988 AllocBeforeWrite(iLen
);
989 strcpy(m_pchData
, buffer
);
991 if ( buffer
!= s_szScratch
)
997 // ----------------------------------------------------------------------------
998 // misc other operations
999 // ----------------------------------------------------------------------------
1000 bool wxString::Matches(const char *pszMask
) const
1002 // check char by char
1004 for ( pszTxt
= c_str(); *pszMask
!= '\0'; pszMask
++, pszTxt
++ ) {
1005 switch ( *pszMask
) {
1007 if ( *pszTxt
== '\0' )
1016 // ignore special chars immediately following this one
1017 while ( *pszMask
== '*' || *pszMask
== '?' )
1020 // if there is nothing more, match
1021 if ( *pszMask
== '\0' )
1024 // are there any other metacharacters in the mask?
1026 const char *pEndMask
= strpbrk(pszMask
, "*?");
1028 if ( pEndMask
!= NULL
) {
1029 // we have to match the string between two metachars
1030 uiLenMask
= pEndMask
- pszMask
;
1033 // we have to match the remainder of the string
1034 uiLenMask
= strlen(pszMask
);
1037 wxString
strToMatch(pszMask
, uiLenMask
);
1038 const char* pMatch
= strstr(pszTxt
, strToMatch
);
1039 if ( pMatch
== NULL
)
1042 // -1 to compensate "++" in the loop
1043 pszTxt
= pMatch
+ uiLenMask
- 1;
1044 pszMask
+= uiLenMask
- 1;
1049 if ( *pszMask
!= *pszTxt
)
1055 // match only if nothing left
1056 return *pszTxt
== '\0';
1059 // Count the number of chars
1060 int wxString::Freq(char ch
) const
1064 for (int i
= 0; i
< len
; i
++)
1066 if (GetChar(i
) == ch
)
1072 // convert to upper case, return the copy of the string
1073 wxString
wxString::Upper() const
1074 { wxString
s(*this); return s
.MakeUpper(); }
1076 // convert to lower case, return the copy of the string
1077 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1079 int wxString::sprintf(const char *pszFormat
, ...)
1082 va_start(argptr
, pszFormat
);
1083 int iLen
= PrintfV(pszFormat
, argptr
);
1088 // ---------------------------------------------------------------------------
1089 // standard C++ library string functions
1090 // ---------------------------------------------------------------------------
1091 #ifdef wxSTD_STRING_COMPATIBILITY
1093 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1095 wxASSERT( str
.GetStringData()->IsValid() );
1096 wxASSERT( nPos
<= Len() );
1098 if ( !str
.IsEmpty() ) {
1100 char *pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1101 strncpy(pc
, c_str(), nPos
);
1102 strcpy(pc
+ nPos
, str
);
1103 strcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1104 strTmp
.UngetWriteBuf();
1111 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1113 wxASSERT( str
.GetStringData()->IsValid() );
1114 wxASSERT( nStart
<= Len() );
1116 const char *p
= strstr(c_str() + nStart
, str
);
1118 return p
== NULL
? npos
: p
- c_str();
1121 // VC++ 1.5 can't cope with the default argument in the header.
1122 #if !defined(__VISUALC__) || defined(__WIN32__)
1123 size_t wxString::find(const char* sz
, size_t nStart
, size_t n
) const
1125 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1129 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1130 #if !defined(__BORLANDC__)
1131 size_t wxString::find(char ch
, size_t nStart
) const
1133 wxASSERT( nStart
<= Len() );
1135 const char *p
= strchr(c_str() + nStart
, ch
);
1137 return p
== NULL
? npos
: p
- c_str();
1141 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1143 wxASSERT( str
.GetStringData()->IsValid() );
1144 wxASSERT( nStart
<= Len() );
1146 // # could be quicker than that
1147 const char *p
= c_str() + (nStart
== npos
? Len() : nStart
);
1148 while ( p
>= c_str() + str
.Len() ) {
1149 if ( strncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1150 return p
- str
.Len() - c_str();
1157 // VC++ 1.5 can't cope with the default argument in the header.
1158 #if !defined(__VISUALC__) || defined(__WIN32__)
1159 size_t wxString::rfind(const char* sz
, size_t nStart
, size_t n
) const
1161 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1164 size_t wxString::rfind(char ch
, size_t nStart
) const
1166 wxASSERT( nStart
<= Len() );
1168 const char *p
= strrchr(c_str() + nStart
, ch
);
1170 return p
== NULL
? npos
: p
- c_str();
1174 wxString
wxString::substr(size_t nStart
, size_t nLen
) const
1176 // npos means 'take all'
1180 wxASSERT( nStart
+ nLen
<= Len() );
1182 return wxString(c_str() + nStart
, nLen
== npos
? 0 : nLen
);
1185 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1187 wxString
strTmp(c_str(), nStart
);
1188 if ( nLen
!= npos
) {
1189 wxASSERT( nStart
+ nLen
<= Len() );
1191 strTmp
.append(c_str() + nStart
+ nLen
);
1198 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const char *sz
)
1200 wxASSERT( nStart
+ nLen
<= Strlen(sz
) );
1204 strTmp
.append(c_str(), nStart
);
1206 strTmp
.append(c_str() + nStart
+ nLen
);
1212 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, char ch
)
1214 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1217 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1218 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1220 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1223 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1224 const char* sz
, size_t nCount
)
1226 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1229 #endif //std::string compatibility
1231 // ============================================================================
1233 // ============================================================================
1235 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1236 #define ARRAY_MAXSIZE_INCREMENT 4096
1237 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1238 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1241 #define STRING(p) ((wxString *)(&(p)))
1244 wxArrayString::wxArrayString()
1248 m_pItems
= (char **) NULL
;
1252 wxArrayString::wxArrayString(const wxArrayString
& src
)
1256 m_pItems
= (char **) NULL
;
1261 // assignment operator
1262 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1267 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1268 Alloc(src
.m_nCount
);
1270 // we can't just copy the pointers here because otherwise we would share
1271 // the strings with another array
1272 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1275 if ( m_nCount
!= 0 )
1276 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(char *));
1282 void wxArrayString::Grow()
1284 // only do it if no more place
1285 if( m_nCount
== m_nSize
) {
1286 if( m_nSize
== 0 ) {
1287 // was empty, alloc some memory
1288 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1289 m_pItems
= new char *[m_nSize
];
1292 // otherwise when it's called for the first time, nIncrement would be 0
1293 // and the array would never be expanded
1294 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1296 // add 50% but not too much
1297 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1298 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1299 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1300 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1301 m_nSize
+= nIncrement
;
1302 char **pNew
= new char *[m_nSize
];
1304 // copy data to new location
1305 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(char *));
1307 // delete old memory (but do not release the strings!)
1308 wxDELETEA(m_pItems
);
1315 void wxArrayString::Free()
1317 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1318 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1322 // deletes all the strings from the list
1323 void wxArrayString::Empty()
1330 // as Empty, but also frees memory
1331 void wxArrayString::Clear()
1338 wxDELETEA(m_pItems
);
1342 wxArrayString::~wxArrayString()
1346 wxDELETEA(m_pItems
);
1349 // pre-allocates memory (frees the previous data!)
1350 void wxArrayString::Alloc(size_t nSize
)
1352 wxASSERT( nSize
> 0 );
1354 // only if old buffer was not big enough
1355 if ( nSize
> m_nSize
) {
1357 wxDELETEA(m_pItems
);
1358 m_pItems
= new char *[nSize
];
1365 // searches the array for an item (forward or backwards)
1366 int wxArrayString::Index(const char *sz
, bool bCase
, bool bFromEnd
) const
1369 if ( m_nCount
> 0 ) {
1370 size_t ui
= m_nCount
;
1372 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1379 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1380 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1388 // add item at the end
1389 void wxArrayString::Add(const wxString
& str
)
1391 wxASSERT( str
.GetStringData()->IsValid() );
1395 // the string data must not be deleted!
1396 str
.GetStringData()->Lock();
1397 m_pItems
[m_nCount
++] = (char *)str
.c_str();
1400 // add item at the given position
1401 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
1403 wxASSERT( str
.GetStringData()->IsValid() );
1405 wxCHECK_RET( nIndex
<= m_nCount
, ("bad index in wxArrayString::Insert") );
1409 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
1410 (m_nCount
- nIndex
)*sizeof(char *));
1412 str
.GetStringData()->Lock();
1413 m_pItems
[nIndex
] = (char *)str
.c_str();
1418 // removes item from array (by index)
1419 void wxArrayString::Remove(size_t nIndex
)
1421 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Remove") );
1424 Item(nIndex
).GetStringData()->Unlock();
1426 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
1427 (m_nCount
- nIndex
- 1)*sizeof(char *));
1431 // removes item from array (by value)
1432 void wxArrayString::Remove(const char *sz
)
1434 int iIndex
= Index(sz
);
1436 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
1437 _("removing inexistent element in wxArrayString::Remove") );
1442 // ----------------------------------------------------------------------------
1444 // ----------------------------------------------------------------------------
1446 // we can only sort one array at a time with the quick-sort based
1449 #include <wx/thread.h>
1451 // need a critical section to protect access to gs_compareFunction and
1452 // gs_sortAscending variables
1453 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
1455 // call this before the value of the global sort vars is changed/after
1456 // you're finished with them
1457 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
1458 gs_critsectStringSort = new wxCriticalSection; \
1459 gs_critsectStringSort->Enter()
1460 #define END_SORT() gs_critsectStringSort->Leave(); \
1461 delete gs_critsectStringSort; \
1462 gs_critsectStringSort = NULL
1464 #define START_SORT()
1466 #endif // wxUSE_THREADS
1468 // function to use for string comparaison
1469 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
1471 // if we don't use the compare function, this flag tells us if we sort the
1472 // array in ascending or descending order
1473 static bool gs_sortAscending
= TRUE
;
1475 // function which is called by quick sort
1476 static int wxStringCompareFunction(const void *first
, const void *second
)
1478 wxString
*strFirst
= (wxString
*)first
;
1479 wxString
*strSecond
= (wxString
*)second
;
1481 if ( gs_compareFunction
) {
1482 return gs_compareFunction(*strFirst
, *strSecond
);
1485 int result
= strcmp(strFirst
->c_str(), strSecond
->c_str());
1487 return gs_sortAscending
? result
: -result
;
1491 // sort array elements using passed comparaison function
1492 void wxArrayString::Sort(CompareFunction compareFunction
)
1496 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1497 gs_compareFunction
= compareFunction
;
1504 void wxArrayString::Sort(bool reverseOrder
)
1508 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1509 gs_sortAscending
= !reverseOrder
;
1516 void wxArrayString::DoSort()
1518 // just sort the pointers using qsort() - of course it only works because
1519 // wxString() *is* a pointer to its data
1520 qsort(m_pItems
, m_nCount
, sizeof(char *), wxStringCompareFunction
);