Contents Up Previous Next

wxString overview

Class: wxString

Strings are used very frequently in most programs. There is no direct support in the C++ language for strings. A string class can be useful in many situations: it not only makes the code shorter and easier to read, it also provides more security, because we don't have to deal with pointer acrobatics.

wxString is available in two versions: a cut-down wxWindows, copyright-free version, and a much more powerful GNU-derived version. The default is the GNU-derived, fully-featured version, ported and revised by Stefan Hammes.

For backward compatibility most of the member functions of the original wxWindows wxString class have been included, except some 'dangerous' functions.

wxString can be compiled under MSW, UNIX and VMS (see below). The function names have been capitalized to be consistent with the wxWindows naming scheme.

The reasons for not using the GNU string class directly are:

The GNU code comes with certain copyright restrictions. If you can't live with these, you will need to use the cut-down wxString class instead, by editing wx_setup.h and appropriate wxWindows makefiles.

Copyright of the original GNU code portion
Features/Additions/Modifications
Function calls
Header files
Test program
Compilers
GNU Documentation
Regular Expressions


Copyright of the original GNU code portion

Copyright (C) 1988, 1991, 1992 Free Software Foundation, Inc. written by Doug Lea (dl@rocky.oswego.edu)

This file is part of the GNU C++ Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.


Features/Additions/Modifications

The wxString class offers many string handling functions and a support for regular expressions. This gives powerful, easy-to-use pattern-matching functionality. See below for a discussion of the GNU features of wxString. See also the header file 'wxstrgnu.h' which shows all member functions.

As stated above, there are extensions to the wxString class. This includes the including of the 'old' wxString class member functions. Below is a list of the additional member functions:


Function calls

When using wxString objects as parameters to other functions you should note the following:

void f1(const char *s){}
void f2(char *s){}

main(){
  wxString aString;
  f1(aString); // ok
  f2(aString); // error
  f2(wxCHARARG(aString)); // ok
  printf("%s",aString); // NO compilation error, but a runtime error.
  printf("%s",aString.Chars()); // ok
  printf("%s",wxCHARARG(aString)); // ok
}

Header files

For DOS and UNIX we use a stub-headerfile include/base/wxstring.h which includes the two headerfiles in the contrib/wxstring directory, namely contrib/wxstring/wxstrgnu.h and contrib/wxstring/wxregex.h. If there is a headerfile contrib/wxstring/wxstring.h, please delete it. It will cause problems in the VMS compilation.

For VMS we have to do an addition due to the not very intelligent inclusion mechanism of the VMS C++ compiler: In the VMS-Makefile, the include-file search path is augmented with the contrib/wxstring directory, so that the correct headerfiles can be included.

So you have only to specify

#define USE_GNU_WXSTRING 1
in include/base/wx_setup.h to use the wxString class.


Test program

Stefan Hammes has included a test program test.cc in the contrib/wxstring directory for many features of wxString and wxRegex. It also tests Stefan's extensions. When running the compiled program, there should be NO assert-errors if everything is OK. When compiling the test program, you can ignore warnings about unused variables. They occur because Stefan has used a special method of initializing all variables to the same start values before each test.


Compilers

wxString and wxRegex have been compiled successfully with the following compilers (it should work on nearly every C++ compiler):

Warnings about type conversion or assignments can be ignored.


GNU Documentation

Below is the original GNU wxString and wxRegex documentation. It describes most functions of the classes. The function names have been capitalized to be consistent with the wxWindows naming scheme. The examples are integrated into the test program.

Copyright (C) 1988, 1991, 1992 Free Software Foundation, Inc.

Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.

Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided also that the section entitled "GNU Library General Public License" is included exactly as in the original, and provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.

Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that the section entitled "GNU Library General Public License" and this permission notice may be included in translations approved by the Free Software Foundation instead of in the original English.


The wxString class

The 'wxString' class is designed to extend GNU C++ to support string processing capabilities similar to those in languages like Awk. The class provides facilities that ought to be convenient and efficient enough to be useful replacements for 'char*' based processing via the C string library (i.e., 'strcpy, strcmp,' etc.) in many applications. Many details about wxString representations are described in the Representation section.

A separate 'wxSubString' class supports substring extraction and modification operations. This is implemented in a way that user programs never directly construct or represent substrings, which are only used indirectly via wxString operations.

Another separate class, 'wxRegex' is also used indirectly via wxString operations in support of regular expression searching, matching, and the like. The wxRegex class is based entirely on the GNU Emacs regex functions. See Regular Expressions for a full explanation of regular expression syntax. (For implementation details, see the internal documentation in files wxregex.h and wxregex.cc).


Constructor examples

Strings are initialized and assigned as in the following examples:

wxString x; Set x to the nil string. This is different from the original GNU code which sets a strings also to nil when it is assign 0 or "".

wxString x = "Hello"; wxString y("Hello"); Set x and y to a copy of the string "Hello".

wxString x = 'A'; wxString y('A'); Set x and y to the string value "A".

wxString u = x; wxString v(x); Set u and v to the same string as wxString x

wxString u = x.At(1,4); wxString v(x.At(1,4)); Set u and v to the length 4 substring of x starting at position 1 (counting indexes from 0).

wxString x("abc", 2); Sets x to "ab", i.e., the first 2 characters of "abc".

There are no directly accessible forms for declaring wxSubString variables.

The declaration wxRegex r("[a-zA-Z_][a-zA-Z0-9_]*"); creates compiled regular expression suitable for use in wxString operations described below. (In this case, one that matches any C++ identifier). The first argument may also be a wxString. Be careful in distinguishing the role of backslashes in quoted GNU C++ 'char*' constants versus those in Regexes. For example, a wxRegex that matches either one or more tabs or all strings beginning with "ba" and ending with any number of occurrences of "na" could be declared as

   wxRegex r = "\\(\t+\\)\\|\\(ba\\(na\\)*\\)"
Note that only one backslash is needed to signify the tab, but two are needed for the parenthesization and virgule, since the GNU C++ lexical analyzer decodes and strips backslashes before they are seen by wxRegex.

There are three additional optional arguments to the wxRegex constructor that are less commonly useful:

fast (default 0) 'fast' may be set to true (1) if the wxRegex should be "fast-compiled". This causes an additional compilation step that is generally worthwhile if the wxRegex will be used many times.

bufsize (default max(40, length of the string)) This is an estimate of the size of the internal compiled expression. Set it to a larger value if you know that the expression will require a lot of space. If you do not know, do not worry: realloc is used if necessary.

transtable (default none == 0) The address of a byte translation table (a char[256]) that translates each character before matching.

As a convenience, several Regexes are predefined and usable in any program. Here are their declarations from wxString.h.

     extern wxRegex RXwhite;      // = "[ \n\t]+"
     extern wxRegex RXint;        // = "-?[0-9]+"
     extern wxRegex RXdouble;     // = "-?\\(\\([0-9]+\\.[0-9]*\\)\\|
                                  //    \\([0-9]+\\)\\|
                                  //    \\(\\.[0-9]+\\)\\)
                                  //    \\([eE][---+]?[0-9]+\\)?"
     extern wxRegex RXalpha;      // = "[A-Za-z]+"
     extern wxRegex RXlowercase;  // = "[a-z]+"
     extern wxRegex RXuppercase;  // = "[A-Z]+"
     extern wxRegex RXalphanum;   // = "[0-9A-Za-z]+"
     extern wxRegex RXidentifier; // = "[A-Za-z_][A-Za-z0-9_]*"

Examples

Most wxString class capabilities are best shown via example. The examples below use the following declarations.

         wxString x = "Hello";
         wxString y = "world";
         wxString n = "123";
         wxString z;
         char *s = ",";
         wxString lft, mid, rgt;
         wxRegex  r = "e[a-z]*o";
         wxRegex  r2("/[a-z]*/");
         char   c;
         int    i, pos, len;
         double f;
         wxString words[10];
         words[0] = "a";
         words[1] = "b";
         words[2] = "c";

Comparing, Searching and Matching examples

The usual lexicographic relational operators ('==, !=, <, <=, >, >=') are defined. A functional form 'compare(wxString, wxString)' is also provided, as is 'fcompare(wxString, wxString)', which compares Strings without regard for upper vs. lower case.

All other matching and searching operations are based on some form of the (non-public) 'match' and 'search' functions. 'match' and 'search' differ in that 'match' attempts to match only at the given starting position, while 'search' starts at the position, and then proceeds left or right looking for a match. As seen in the following examples, the second optional 'startpos' argument to functions using 'match' and 'search' specifies the starting position of the search: If non-negative, it results in a left-to-right search starting at position 'startpos', and if negative, a right-to-left search starting at position 'x.Length() + startpos'. In all cases, the index returned is that of the beginning of the match, or -1 if there is no match.

Three wxString functions serve as front ends to 'search' and 'match'. 'index' performs a search, returning the index, 'matches' performs a match, returning nonzero (actually, the length of the match) on success, and 'contains' is a boolean function performing either a search or match, depending on whether an index argument is provided:

x.Index("lo") Returns the zero-based index of the leftmost occurrence of substring "lo" (3, in this case). The argument may be a wxString, wxSubString, char, char*, or wxRegex.

x.Index("l", 2) Returns the index of the first of the leftmost occurrence of "l" found starting the search at position x[2], or 2 in this case.

x.Index("l", -1) Returns the index of the rightmost occurrence of "l", or 3 here.

x.Index("l", -3) Returns the index of the rightmost occurrence of "l" found by starting the search at the 3rd to the last position of x, returning 2 in this case.

pos = r.Search("leo", 3, len, 0) Returns the index of r in the char* string of length 3, starting at position 0, also placing the length of the match in reference parameter len.

x.Contains("He") Returns nonzero if the wxString x contains the substring "He". The argument may be a wxString, wxSubString, char, char*, or wxRegex.

x.Contains("el", 1) Returns nonzero if x contains the substring "el" at position 1. As in this example, the second argument to 'contains', if present, means to match the substring only at that position, and not to search elsewhere in the string.

x.Contains(RXwhite); Returns nonzero if x contains any whitespace (space, tab, or newline). Recall that 'RXwhite' is a global whitespace wxRegex.

x.Matches("lo", 3) Returns nonzero if x starting at position 3 exactly matches "lo", with no trailing characters (as it does in this example).

x.Matches(r) Returns nonzero if wxString x as a whole matches wxRegex r.

int f = x.Freq("l") Returns the number of distinct, nonoverlapping matches to the argument (2 in this case).


Substring extraction examples

Substrings may be extracted via the 'at', 'before', 'through', 'from', and 'after' functions. These behave as either lvalues or rvalues.

z = x.At(2, 3) Sets wxString z to be equal to the length 3 substring of wxString x starting at zero-based position 2, setting z to "llo" in this case. A nil wxString is returned if the arguments don't make sense.

x.At(2, 2) = "r" Sets what was in positions 2 to 3 of x to "r", setting x to "Hero" in this case. As indicated here, wxSubString assignments may be of different lengths.

x.At("He") = "je"; x("He") is the substring of x that matches the first occurrence of it's argument. The substitution sets x to "jello". If "He" did not occur, the substring would be nil, and the assignment would have no effect.

x.At("l", -1) = "i"; Replaces the rightmost occurrence of "l" with "i", setting x to "Helio".

z = x.At(r) Sets wxString z to the first match in x of wxRegex r, or "ello" in this case. A nil wxString is returned if there is no match.

z = x.Before("o") Sets z to the part of x to the left of the first occurrence of "o", or "Hell" in this case. The argument may also be a wxString, wxSubString, or wxRegex. (If there is no match, z is set to "".)

x.Before("ll") = "Bri"; Sets the part of x to the left of "ll" to "Bri", setting x to "Brillo".

z = x.Before(2) Sets z to the part of x to the left of x[2], or "He" in this case.

z = x.After("Hel") Sets z to the part of x to the right of "Hel", or "lo" in this case.

z = x.Through("el") Sets z to the part of x up and including "el", or "Hel" in this case.

z = x.From("el") Sets z to the part of x from "el" to the end, or "ello" in this case.

x.After("Hel") = "p"; Sets x to "Help";

z = x.After(3) Sets z to the part of x to the right of x[3] or "o" in this case.

z = " ab c"; z = z.After(RXwhite) Sets z to the part of its old string to the right of the first group of whitespace, setting z to "ab c"; Use GSub(below) to strip out multiple occurrences of whitespace or any pattern.

x[0] = 'J'; Sets the first element of x to 'J'. x[i] returns a reference to the ith element of x, or triggers an error if i is out of range.

CommonPrefix(x, "Help") Returns the wxString containing the common prefix of the two Strings or "Hel" in this case.

CommonSuffix(x, "to") Returns the wxString containing the common suffix of the two Strings or "o" in this case.


Concatenation examples

z = x + s + ' ' + y.At("w") + y.After("w") + "."; Sets z to "Hello, world."

x += y; Sets x to "Helloworld".

Cat(x, y, z) A faster way to say z = x + y.

Cat(z, y, x, x) Double concatenation; A faster way to say x = z + y + x.

y.Prepend(x); A faster way to say y = x + y.

z = Replicate(x, 3); Sets z to "HelloHelloHello".

z = Join(words, 3, "/") Sets z to the concatenation of the first 3 Strings in wxString array words, each separated by "/", setting z to "a/b/c" in this case. The last argument may be "" or 0, indicating no separation.


Other manipulation examples

z = "this string has five words"; i = Split(z, words, 10, RXwhite); Sets up to 10 elements of wxString array words to the parts of z separated by whitespace, and returns the number of parts actually encountered (5 in this case). Here, words[0] = "this", words[1] = "string", etc. The last argument may be any of the usual. If there is no match, all of z ends up in words[0]. The words array is *not* dynamically created by split.

int nmatches x.GSub("l","ll") Substitutes all original occurrences of "l" with "ll", setting x to "Hellllo". The first argument may be any of the usual, including wxRegex. If the second argument is "" or 0, all occurrences are deleted. gsub returns the number of matches that were replaced.

z = x + y; z.Del("loworl"); Deletes the leftmost occurrence of "loworl" in z, setting z to "Held".

z = Reverse(x) Sets z to the reverse of x, or "olleH".

z = Upcase(x) Sets z to x, with all letters set to uppercase, setting z to "HELLO".

z = Downcase(x) Sets z to x, with all letters set to lowercase, setting z to "hello"

z = Capitalize(x) Sets z to x, with the first letter of each word set to uppercase, and all others to lowercase, setting z to "Hello"

x.Reverse(), x.Upcase(), x.Downcase(), x.Capitalize() in-place, self-modifying versions of the above.


Reading, Writing and Conversion examples

cout << x Writes out x.

cout << x.At(2, 3) Writes out the substring "llo".

cin >> x Reads a whitespace-bounded string into x.

x.Length() Returns the length of wxString x (5, in this case).

s = (const char*)x Can be used to extract the 'char*' char array. This coercion is useful for sending a wxString as an argument to any function expecting a 'const char*' argument (like 'atoi', and 'File::open'). This operator must be used with care, since the conversion returns a pointer to 'wxString' internals without copying the characters: The resulting '(char*)' is only valid until the next wxString operation, and you must not modify it. (The conversion is defined to return a const value so that GNU C++ will produce warning and/or error messages if changes are attempted.)


Regular Expressions

The following are extracts from GNU documentation.


Regular Expression Overview

Regular expression matching allows you to test whether a string fits into a specific syntactic shape. You can also search a string for a substring that fits a pattern.

A regular expression describes a set of strings. The simplest case is one that describes a particular string; for example, the string 'foo' when regarded as a regular expression matches 'foo' and nothing else. Nontrivial regular expressions use certain special constructs so that they can match more than one string. For example, the regular expression 'foo\|bar' matches either the string 'foo' or the string 'bar'; the regular expression 'c[ad]*r' matches any of the strings 'cr', 'car', 'cdr', 'caar', 'cadddar' and all other such strings with any number of 'a''s and 'd''s.

The first step in matching a regular expression is to compile it. You must supply the pattern string and also a pattern buffer to hold the compiled result. That result contains the pattern in an internal format that is easier to use in matching.

Having compiled a pattern, you can match it against strings. You can match the compiled pattern any number of times against different strings.


Syntax of Regular Expressions

Regular expressions have a syntax in which a few characters are special constructs and the rest are "ordinary". An ordinary character is a simple regular expression which matches that character and nothing else. The special characters are '\$', '^', '.', '*', '+', '?', '[', ']' and '\'. Any other character appearing in a regular expression is ordinary, unless a '\' precedes it.

For example, 'f' is not a special character, so it is ordinary, and therefore 'f' is a regular expression that matches the string 'f' and no other string. (It does *not* match the string 'ff'.) Likewise, 'o' is a regular expression that matches only 'o'.

Any two regular expressions A and B can be concatenated. The result is a regular expression which matches a string if A matches some amount of the beginning of that string and B matches the rest of the string.

As a simple example, we can concatenate the regular expressions 'f' and 'o' to get the regular expression 'fo', which matches only the string 'fo'. Still trivial.

Note: for Unix compatibility, special characters are treated as ordinary ones if they are in contexts where their special meanings make no sense. For example, '*foo' treats '*' as ordinary since there is no preceding expression on which the '*' can act. It is poor practice to depend on this behavior; better to quote the special character anyway, regardless of where is appears.

The following are the characters and character sequences which have special meaning within regular expressions. Any character not mentioned here is not special; it stands for exactly itself for the purposes of searching and matching.