The BString
is a string allocation and manipulation class. The object takes
care of allocating and freeing memory for you, and provides a number of
character search, comparison, and manipulation functions in a variety of
flavors:
FindFirst()
,
FindLast()
,
Prepend()
,
Append()
,
Insert()
,
Remove()
,
RemoveSet()
,
and so on. The class also defines a number of
operators that map to these functions; for example, the
+= operator is
the same as the
Append()
function. The operators make
BString
objects particularly easy to work with.
This document describes some global C functions and operators that act
like BString
functions. The global
Compare()
and
ICompare()
functions let
you compare two BString
s
that are passed as arguments; they're meant to
be used as hook functions that are called from within a sorting routine
(such as qsort()
). The global operators are defined so you don't have to
worry about the order of the operands.
Warning
BString
is not thread safe. You shouldn't try to access the same
BString
object from two different threads at the same time.
Currently, BString
only supports assignment and retrieval of strings
that contain single-byte characters. If you want to use a
BString
to
store a string that contains multi-byte (UTF8) characters, you have to
flatten the string yourself and adjust the character count arguments
accordingly.
Assigning and Retrieving String Data
To assign a BString
's
string, you pass the string to the object's
constructor, to
SetTo()
,
or you use the
= or
<<
operators:
BString
string
("8 Bits");
BString
string
;
string
.SetTo
("8 Bits");
BString
string
= "8 Bits";
BString
string
;
string
<< (int32)8 << " Bits";
There's also an
Adopt()
function that let's you move data from one
BString
object to another. In all cases, the
BString
object takes care of
allocating storage for you—the object is guaranteed to be "big
enough" to contain the string data.
The
String()
function retrieves the object's string:
myButton
->SetLabel
(string
.String
());
ByteAt()
returns a single character, located by index. You can also get a
character by using the
[]
operator; the following returns the string's
first character:
char c
= string
[0];
If you want to access a
BString
's
data directly, you call
LockBuffer()
,
and then call
UnlockBuffer()
when you're finished. Between these two
calls, you can manipulate the string data, but you mustn't call any other
BString
function:
int32 len
= string
.Length
()+1
char *stringData
= string
.LockBuffer
(len
);
stringData
[0] = 'd';
strcat
(stringData
, " button");
string
.UnlockBuffer
(len
+strlen
(" button"));