wxString is a class representing a character string. Please see the wxString overview for more information about it. As explained there, wxString implements about 90% of methods of the std::string class (iterators are not supported, nor all methods which use them). These standard functions are not documented in this manual so please see the STL documentation. The behaviour of all these functions is identical to the behaviour described there.
Derived from
None
Include files
<wx/string.h>
Predefined objects
Objects:
wxEmptyString
See also
Function groups
Constructors and assignment operators
String length
Character access
Concatenation
Comparison
Substring extraction
Case conversion
Searching and replacing
Conversion to numbers
Writing values into the string
Memory management
Miscellaneous
wxWindows 1.xx compatibility functions
std::string compatibility functions
wxString::wxString
wxString::~wxString
wxString::Alloc
wxString::Append
wxString::AfterFirst
wxString::AfterLast
wxString::BeforeFirst
wxString::BeforeLast
wxString::c_str
wxString::Clear
wxString::Cmp
wxString::CmpNoCase
wxString::CompareTo
wxString::Contains
wxString::Empty
wxString::Find
wxString::First
wxString::Format
wxString::FormatV
wxString::Freq
wxString::GetChar
wxString::GetData
wxString::GetWritableChar
wxString::GetWriteBuf
wxString::Index
wxString::IsAscii
wxString::IsEmpty
wxString::IsNull
wxString::IsNumber
wxString::IsSameAs
wxString::IsSameAs
wxString::IsWord
wxString::Last
wxString::Left
wxString::Len
wxString::Length
wxString::Lower
wxString::LowerCase
wxString::MakeLower
wxString::MakeUpper
wxString::Matches
wxString::Mid
wxString::Pad
wxString::Prepend
wxString::Printf
wxString::PrintfV
wxString::Remove
wxString::RemoveLast
wxString::Replace
wxString::Right
wxString::SetChar
wxString::Shrink
wxString::sprintf
wxString::StartsWith
wxString::Strip
wxString::SubString
wxString::ToDouble
wxString::ToLong
wxString::ToULong
wxString::Trim
wxString::Truncate
wxString::UngetWriteBuf
wxString::Upper
wxString::UpperCase
wxString::operator!
wxString::operator =
wxString::operator +
wxString::operator +=
wxString::operator []
wxString::operator ()
wxString::operator <<
wxString::operator >>
wxString::operator const char*
Comparison operators
A strign may be constructed either from a C string, (some number of copies of) a single character or a wide (UNICODE) string. For all constructors (except the default which creates an empty string) there is also a corresponding assignment operator.
These functions return the string length and check whether the string is empty or empty it.
Len
IsEmpty
operator!
Empty
Clear
Many functions in this section take a character index in the string. As with C strings and/or arrays, the indices start from 0, so the first character of a string is string[0]. Attempt to access a character beyond the end of the string (which may be even 0 if the string is empty) will provocate an assert failure in debug build, but no checks are done in release builds.
This section also contains both implicit and explicit conversions to C style strings. Although implicit conversion is quite convenient, it is advised to use explicit c_str() method for the sake of clarity. Also see overview for the cases where it is necessary to use it.
GetChar
GetWritableChar
SetChar
Last
operator []
c_str
operator const char*
Anything may be concatenated (appended to) with a string. However, you can't append something to a C string (including literal constants), so to do this it should be converted to a wxString first.
operator <<
operator +=
operator +
Append
Prepend
The default comparison function Cmp is case-sensitive and so is the default version of IsSameAs. For case insensitive comparisons you should use CmpNoCase or give a second parameter to IsSameAs. This last function is may be more convenient if only equality of the strings matters because it returns a boolean true value if the strings are the same and not 0 (which is usually FALSE in C) as Cmp() does.
Matches is a poor man's regular expression matcher: it only understands '*' and '?' metacharacters in the sense of DOS command line interpreter.
StartsWith is helpful when parsing a line of text which should start with some predefined prefix and is more efficient than doing direct string comparaison as you would also have to precalculate the length of the prefix then.
Cmp
CmpNoCase
IsSameAs
Matches
StartsWith
These functions allow to extract substring from this string. All of them don't modify the original string and return a new string containing the extracted substring.
Mid
operator()
Left
Right
BeforeFirst
BeforeLast
AfterFirst
AfterLast
StartsWith
The MakeXXX() variants modify the string in place, while the other functions return a new string which containts the original text converted to the upper or lower case and leave the original string unchanged.
MakeUpper
Upper
MakeLower
Lower
These functions replace the standard strchr() and strstr() functions.
The string provides functions for conversion to signed and unsigned integer and floating point numbers. All three functions take a pointer to the variable to put the numeric value in and return TRUE if the entire string could be converted to a number.
Both formatted versions (Printf) and stream-like insertion operators exist (for basic types only). Additionally, the Format function allows to use simply append formatted value to a string:
// the following 2 snippets are equivalent wxString s = "..."; s += wxString::Format("%d", n); wxString s; s.Printf("...%d", n);Format
These are "advanced" functions and they will be needed quite rarily. Alloc and Shrink are only interesting for optimization purposes. GetWriteBuf may be very useful when working with some external API which requires the caller to provide a writable buffer, but extreme care should be taken when using it: before performing any other operation on the string UngetWriteBuf must be called!
Alloc
Shrink
GetWriteBuf
UngetWriteBuf
Other string functions.
These functions are deprecated, please consider using new wxWindows 2.0 functions instead of them (or, even better, std::string compatible variants).
SubString
sprintf
CompareTo
Length
Freq
LowerCase
UpperCase
Strip
Index
Remove
First
Last
Contains
IsNull
IsAscii
IsNumber
IsWord
The supported functions are only listed here, please see any STL reference for their documentation.
// take nLen chars starting at nPos wxString(const wxString& str, size_t nPos, size_t nLen); // take all characters from pStart to pEnd (poor man's iterators) wxString(const void *pStart, const void *pEnd); // lib.string.capacity // return the length of the string size_t size() const; // return the length of the string size_t length() const; // return the maximum size of the string size_t max_size() const; // resize the string, filling the space with c if c != 0 void resize(size_t nSize, char ch = '\0'); // delete the contents of the string void clear(); // returns true if the string is empty bool empty() const; // lib.string.access // return the character at position n char at(size_t n) const; // returns the writable character at position n char& at(size_t n); // lib.string.modifiers // append a string wxString& append(const wxString& str); // append elements str[pos], ..., str[pos+n] wxString& append(const wxString& str, size_t pos, size_t n); // append first n (or all if n == npos) characters of sz wxString& append(const char *sz, size_t n = npos); // append n copies of ch wxString& append(size_t n, char ch); // same as `this_string = str' wxString& assign(const wxString& str); // same as ` = str[pos..pos + n] wxString& assign(const wxString& str, size_t pos, size_t n); // same as `= first n (or all if n == npos) characters of sz' wxString& assign(const char *sz, size_t n = npos); // same as `= n copies of ch' wxString& assign(size_t n, char ch); // insert another string wxString& insert(size_t nPos, const wxString& str); // insert n chars of str starting at nStart (in str) wxString& insert(size_t nPos, const wxString& str, size_t nStart, size_t n); // insert first n (or all if n == npos) characters of sz wxString& insert(size_t nPos, const char *sz, size_t n = npos); // insert n copies of ch wxString& insert(size_t nPos, size_t n, char ch); // delete characters from nStart to nStart + nLen wxString& erase(size_t nStart = 0, size_t nLen = npos); // replaces the substring of length nLen starting at nStart wxString& replace(size_t nStart, size_t nLen, const char* sz); // replaces the substring with nCount copies of ch wxString& replace(size_t nStart, size_t nLen, size_t nCount, char ch); // replaces a substring with another substring wxString& replace(size_t nStart, size_t nLen, const wxString& str, size_t nStart2, size_t nLen2); // replaces the substring with first nCount chars of sz wxString& replace(size_t nStart, size_t nLen, const char* sz, size_t nCount); // swap two strings void swap(wxString& str); // All find() functions take the nStart argument which specifies the // position to start the search on, the default value is 0. All functions // return npos if there were no match. // find a substring size_t find(const wxString& str, size_t nStart = 0) const; // find first n characters of sz size_t find(const char* sz, size_t nStart = 0, size_t n = npos) const; // find the first occurence of character ch after nStart size_t find(char ch, size_t nStart = 0) const; // rfind() family is exactly like find() but works right to left // as find, but from the end size_t rfind(const wxString& str, size_t nStart = npos) const; // as find, but from the end size_t rfind(const char* sz, size_t nStart = npos, size_t n = npos) const; // as find, but from the end size_t rfind(char ch, size_t nStart = npos) const; // find first/last occurence of any character in the set // size_t find_first_of(const wxString& str, size_t nStart = 0) const; // size_t find_first_of(const char* sz, size_t nStart = 0) const; // same as find(char, size_t) size_t find_first_of(char c, size_t nStart = 0) const; // size_t find_last_of (const wxString& str, size_t nStart = npos) const; // size_t find_last_of (const char* s, size_t nStart = npos) const; // same as rfind(char, size_t) size_t find_last_of (char c, size_t nStart = npos) const; // find first/last occurence of any character not in the set // size_t find_first_not_of(const wxString& str, size_t nStart = 0) const; // size_t find_first_not_of(const char* s, size_t nStart = 0) const; // size_t find_first_not_of(char ch, size_t nStart = 0) const; // size_t find_last_not_of(const wxString& str, size_t nStart=npos) const; // size_t find_last_not_of(const char* s, size_t nStart = npos) const; // size_t find_last_not_of(char ch, size_t nStart = npos) const; // All compare functions return a negative, zero or positive value // if the [sub]string is less, equal or greater than the compare() argument. // just like strcmp() int compare(const wxString& str) const; // comparison with a substring int compare(size_t nStart, size_t nLen, const wxString& str) const; // comparison of 2 substrings int compare(size_t nStart, size_t nLen, const wxString& str, size_t nStart2, size_t nLen2) const; // just like strcmp() int compare(const char* sz) const; // substring comparison with first nCount characters of sz int compare(size_t nStart, size_t nLen, const char* sz, size_t nCount = npos) const; // substring extraction wxString substr(size_t nStart = 0, size_t nLen = npos) const;
wxString()
Default constructor.
wxString(const wxString& x)
Copy constructor.
wxString(char ch, size_t n = 1)
Constructs a string of n copies of character ch.
wxString(const char* psz, size_t nLength = wxSTRING_MAXLEN)
Takes first nLength characters from the C string psz. The default value of wxSTRING_MAXLEN means to take all the string.
Note that this constructor may be used even if psz points to a buffer with binary data (i.e. containing NUL characters) as long as you provide the correct value for nLength. However, the default form of it works only with strings without intermediate NULs because it uses strlen() to calculate the effective length and it would not give correct results otherwise.
wxString(const unsigned char* psz, size_t nLength = wxSTRING_MAXLEN)
For compilers using unsigned char: takes first nLength characters from the C string psz. The default value of wxSTRING_MAXLEN means take all the string.
wxString(const wchar_t* psz)
Constructs a string from the wide (UNICODE) string.
~wxString()
String destructor. Note that this is not virtual, so wxString must not be inherited from.
void Alloc(size_t nLen)
Preallocate enough space for wxString to store nLen characters. This function may be used to increase speed when the string is constructed by repeated concatenation as in
// delete all vowels from the string wxString DeleteAllVowels(const wxString& original) { wxString result; size_t len = original.length(); result.Alloc(len); for ( size_t n = 0; n < len; n++ ) { if ( strchr("aeuio", tolower(original[n])) == NULL ) result += original[n]; } return result; }because it will avoid the need of reallocating string memory many times (in case of long strings). Note that it does not set the maximal length of a string - it will still expand if more than nLen characters are stored in it. Also, it does not truncate the existing string (use Truncate() for this) even if its current length is greater than nLen
wxString& Append(const char* psz)
Concatenates psz to this string, returning a reference to it.
wxString& Append(char ch, int count = 1)
Concatenates character ch to this string, count times, returning a reference to it.
wxString AfterFirst(char ch) const
Gets all the characters after the first occurence of ch. Returns the empty string if ch is not found.
wxString AfterLast(char ch) const
Gets all the characters after the last occurence of ch. Returns the whole string if ch is not found.
wxString BeforeFirst(char ch) const
Gets all characters before the first occurence of ch. Returns the whole string if ch is not found.
wxString BeforeLast(char ch) const
Gets all characters before the last occurence of ch. Returns the empty string if ch is not found.
const char * c_str() const
Returns a pointer to the string data.
void Clear()
Empties the string and frees memory occupied by it.
See also: Empty
int Cmp(const char* psz) const
Case-sensitive comparison.
Returns a positive value if the string is greater than the argument, zero if it is equal to it or a negative value if it is less than the argument (same semantics as the standard strcmp() function).
int CmpNoCase(const char* psz) const
Case-insensitive comparison.
Returns a positive value if the string is greater than the argument, zero if it is equal to it or a negative value if it is less than the argument (same semantics as the standard strcmp() function).
#define NO_POS ((int)(-1)) // undefined position enum caseCompare {exact, ignoreCase};int CompareTo(const char* psz, caseCompare cmp = exact) const
Case-sensitive comparison. Returns 0 if equal, 1 if greater or -1 if less.
bool Contains(const wxString& str) const
Returns 1 if target appears anyhere in wxString; else 0.
void Empty()
Makes the string empty, but doesn't free memory occupied by the string.
See also: Clear().
int Find(char ch, bool fromEnd = FALSE) const
Searches for the given character. Returns the starting index, or -1 if not found.
int Find(const char* sz) const
Searches for the given string. Returns the starting index, or -1 if not found.
size_t First(char c)
size_t First(const char* psz) const
size_t First(const wxString& str) const
size_t First(const char ch) const
Returns the first occurrence of the item.
static wxString Format(const wxChar *format, ...)
This static function returns the string containing the result of calling Printf with the passed parameters on it.
See also
static wxString Format(const wxChar *format, va_list argptr)
This static function returns the string containing the result of calling PrintfV with the passed parameters on it.
See also
int Freq(char ch) const
Returns the number of occurrences of ch in the string.
char GetChar(size_t n) const
Returns the character at position n (read-only).
const char* GetData() const
wxWindows compatibility conversion. Returns a constant pointer to the data in the string.
char& GetWritableChar(size_t n)
Returns a reference to the character at position n.
char* GetWriteBuf(size_t len)
Returns a writable buffer of at least len bytes.
Call wxString::UngetWriteBuf as soon as possible to put the string back into a reasonable state.
size_t Index(char ch, int startpos = 0) const
Same as wxString::Find.
size_t Index(const char* sz) const
Same as wxString::Find.
size_t Index(const char* sz, bool caseSensitive = TRUE, bool fromEnd = FALSE) const
Search the element in the array, starting from either side.
If fromEnd is TRUE, reverse search direction.
If caseSensitive, comparison is case sensitive (the default).
Returns the index of the first item matched, or NOT_FOUND.
bool IsAscii() const
Returns TRUE if the string is ASCII.
bool IsEmpty() const
Returns TRUE if the string is NULL.
bool IsNull() const
Returns TRUE if the string is NULL (same as IsEmpty).
bool IsNumber() const
Returns TRUE if the string is a positive or negative integer. Will return FALSE for decimals.
bool IsSameAs(const char* psz, bool caseSensitive = TRUE) const
Test for string equality, case-sensitive (default) or not.
caseSensitive is TRUE by default (case matters).
Returns TRUE if strings are equal, FALSE otherwise.
See also Cmp, CmpNoCase, IsSameAs
bool IsSameAs(char c, bool caseSensitive = TRUE) const
Test whether the string is equal to the single character c. The test is case-sensitive if caseSensitive is TRUE (default) or not if it is FALSE.
Returns TRUE if the string is equal to the character, FALSE otherwise.
See also Cmp, CmpNoCase, IsSameAs
bool IsWord() const
Returns TRUE if the string is a word. TODO: what's the definition of a word?
char Last() const
Returns the last character.
char& Last()
Returns a reference to the last character (writable).
wxString Left(size_t count) const
Returns the first count characters.
wxString Left(char ch) const
Returns all characters before the first occurence of ch. Returns the whole string if ch is not found.
size_t Len() const
Returns the length of the string.
size_t Length() const
Returns the length of the string (same as Len).
wxString Lower() const
Returns this string converted to the lower case.
void LowerCase()
Same as MakeLower.
void MakeLower()
Converts all characters to lower case.
void MakeUpper()
Converts all characters to upper case.
bool Matches(const char* szMask) const
Returns TRUE if the string contents matches a mask containing '*' and '?'.
wxString Mid(size_t first, size_t count = wxSTRING_MAXLEN) const
Returns a substring starting at first, with length count, or the rest of the string if count is the default value.
wxString& Pad(size_t count, char pad = ' ', bool fromRight = TRUE)
Adds count copies of pad to the beginning, or to the end of the string (the default).
Removes spaces from the left or from the right (default).
wxString& Prepend(const wxString& str)
Prepends str to this string, returning a reference to this string.
int Printf(const char* pszFormat, ...)
Similar to the standard function sprintf(). Returns the number of characters written, or an integer less than zero on error.
NB: This function will use a safe version of vsprintf() (usually called vsnprintf()) whenever available to always allocate the buffer of correct size. Unfortunately, this function is not available on all platforms and the dangerous vsprintf() will be used then which may lead to buffer overflows.
int PrintfV(const char* pszFormat, va_list argPtr)
Similar to vprintf. Returns the number of characters written, or an integer less than zero on error.
wxString& Remove(size_t pos)
Same as Truncate. Removes the portion from pos to the end of the string.
wxString& Remove(size_t pos, size_t len)
Removes the len characters from the string, starting at pos.
wxString& RemoveLast()
Removes the last character.
size_t Replace(const char* szOld, const char* szNew, bool replaceAll = TRUE)
Replace first (or all) occurences of substring with another one.
replaceAll: global replace (default), or only the first occurence.
Returns the number of replacements made.
wxString Right(size_t count) const
Returns the last count characters.
void SetChar(size_t n, charch)
Sets the character at position n.
void Shrink()
Minimizes the string's memory. This can be useful after a call to Alloc() if too much memory were preallocated.
void sprintf(const char* fmt)
The same as Printf.
bool StartsWith(const wxChar *prefix, wxString *rest = NULL) const
This function can be used to test if the string starts with the specified prefix. If it does, the function will return TRUE and put the rest of the string (i.e. after the prefix) into rest string if it is not NULL. Otherwise, the function returns FALSE and doesn't modify the rest.
enum stripType {leading = 0x1, trailing = 0x2, both = 0x3};wxString Strip(stripType s = trailing) const
Strip characters at the front and/or end. The same as Trim except that it doesn't change this string.
wxString SubString(size_t from, size_t to) const
Same as Mid.
bool ToDouble(double *val) const
Attempts to convert the string to a floating point number. Returns TRUE on success (the number is stored in the location pointed to by val) or FALSE if the string does not represent such number.
See also
wxString::ToLong,
wxString::ToULong
bool ToLong(long *val) const
Attempts to convert the string to a signed integer. Returns TRUE on success (the number is stored in the location pointed to by val) or FALSE if the string does not represent such number.
See also
wxString::ToDouble,
wxString::ToULong
bool ToULong(unsigned long *val) const
Attempts to convert the string to an unsigned integer. Returns TRUE on success (the number is stored in the location pointed to by val) or FALSE if the string does not represent such number.
See also
wxString::ToDouble,
wxString::ToLong
wxString& Trim(bool fromRight = TRUE)
Removes spaces from the left or from the right (default).
wxString& Truncate(size_t len)
Truncate the string to the given length.
void UngetWriteBuf()
Puts the string back into a reasonable state, after wxString::GetWriteBuf was called.
wxString Upper() const
Returns this string converted to upper case.
void UpperCase()
The same as MakeUpper.
bool operator!() const
Empty string is FALSE, so !string will only return TRUE if the string is empty. This allows the tests for NULLness of a const char * pointer and emptyness of the string to look the same in the code and makes it easier to port old code to wxString.
See also IsEmpty().
wxString& operator =(const wxString& str)
wxString& operator =(const char* psz)
wxString& operator =(char c)
wxString& operator =(const unsigned char* psz)
wxString& operator =(const wchar_t* pwz)
Assignment: the effect of each operation is the same as for the corresponding constructor (see wxString constructors).
Concatenation: all these operators return a new strign equal to the sum of the operands.
wxString operator +(const wxString& x, const wxString& y)
wxString operator +(const wxString& x, const char* y)
wxString operator +(const wxString& x, char y)
wxString operator +(const char* x, const wxString& y)
void operator +=(const wxString& str)
void operator +=(const char* psz)
void operator +=(char c)
Concatenation in place: the argument is appended to the string.
char& operator [](size_t i)
char operator [](size_t i)
char operator [](int i)
Element extraction.
wxString operator ()(size_t start, size_t len)
Same as Mid (substring extraction).
wxString& operator <<(const wxString& str)
wxString& operator <<(const char* psz)
wxString& operator <<(char ch)
Same as +=.
wxString& operator <<(int i)
wxString& operator <<(float f)
wxString& operator <<(double d)
These functions work as C++ stream insertion operators: they insert the given value into the string. Precision or format cannot be set using them, you can use Printf for this.
friend istream& operator >>(istream& is, wxString& str)
Extraction from a stream.
operator const char*() const
Implicit conversion to a C string.
bool operator ==(const wxString& x, const wxString& y)
bool operator ==(const wxString& x, const char* t)
bool operator !=(const wxString& x, const wxString& y)
bool operator !=(const wxString& x, const char* t)
bool operator >(const wxString& x, const wxString& y)
bool operator >(const wxString& x, const char* t)
bool operator >=(const wxString& x, const wxString& y)
bool operator >=(const wxString& x, const char* t)
bool operator <(const wxString& x, const wxString& y)
bool operator <(const wxString& x, const char* t)
bool operator <=(const wxString& x, const wxString& y)
bool operator <=(const wxString& x, const char* t)
Remarks
These comparisons are case-sensitive.