The String

I l @ ve RuBoard

The .NET framework has extensive support for strings. The System namespace has a System.String class that can be used to store text.

The managed extensions to C++ also allow you to use the System.String object through the String extension.

You can define a string under managed C++ as follows :

 String *pS=S"Hello World"; 

These strings are created on the Garbage Collected heap and are subject to lifetime management.

Notice the S prefix to the string literal. All instances of identical strings prefixed by S are essentially the same string. A string literal can also be prefixed with L . This signifies that it is a wide character string:

 String *s=L"This is a wide string"; 

Each string is immutable. Once you've made it you can't change it. However, there are functions in the String object that allow you to create new, altered strings from the original. There is also a StringBuilder class that helps in the process.

Listing 1.4.2 shows an example.

Listing 1.4.2 strings.cpp : Using Managed Strings in C++
 #using <mscorlib.dll> using namespace System; void StringCompare(String *a, String *b) {     Console::WriteLine("a=\ "{ 0} \ " b=\ "{ 1} \ " same string? { 2} \ n",                        a,b,a==b ? S"true":S"false"); } void main() {             String* a=S"Hello";             String* b=S"Hello";             StringCompare(a,b);             a=a->Concat(a,S" World");             StringCompare(a,b);             a=a->Remove(5,6);             StringCompare(a,b);} 

In addition to the String being available as a native type, there are some classes specifically designed to manipulate strings. The StringBuilder class is available from the System::Text namespace, and a stream writer for strings called StringWriter is available in the System::IO namespace.

The StringBuilder class provides a set of string manipulation features such as appending characters to a string or snipping a substring from the middle of a string. The StringWriter provides a stream-style interface to strings and enables you to use the .NET style string formatting features instead of having to rely on sprintf all the time. There is also a complementary StringReader class that can be used to stream in a string as if from a file.

Examples of StringBuilder and StringWriter are in some of the listings in the rest of this chapter, particularly Listing 1.4.10.

I l @ ve RuBoard


C# and the .NET Framework. The C++ Perspective
C# and the .NET Framework
ISBN: 067232153X
EAN: 2147483647
Year: 2001
Pages: 204

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net