標籤彙整: String

C++: Conversion between different kinds of string

Adopt from

http://msdn.microsoft.com/en-us/library/ms235631(vs.80).aspx


CString to char*

CString orig("Hello, World!");
wcout << orig << " (CString)" << endl;

// Convert to a char*
const size_t newsize = 100;
char nstring[newsize];
strcpy_s(nstring, orig);

char * to CString

char *orig = "Hello, World!";
cout << orig << " (char *)" << endl;

// Convert to a CString
CString cstring(orig);
cstring += " (CString)";
cout << cstring << endl;

C#: System.String vs System.Text.StringBuilder

Reference

[1] Professional C# 2008 by Christian Nagel et al.  Wrox Press c 2008


Scenario

You need to modify the string many times. For example, encoding a text file through replacing the original characters by the encoded character, recording the name of people who attend the ceremony…

Solution

Using String

If the result is stored in string, whenever you update the result, a new string object is created. String is an immutable data type, which means that once you initialize a string object, that string object can never change. This is because just enough memory is allocated. A new string object is created if modification is made.

For example,

string result = “far”;

result = result.Replace(‘f’, ‘c’);

// new string object is created and the result will reference to this new object

// the memory allocated for old string object will be collected by garbage collector

Console.WriteLine(result);

// car is printed

Using StringBuilder

When a StringBuilder is created, normally, more memory is allocated that the string actually needed. Hence, two main properties for StringBuilder

Length: indicates the length of the string that it actually contains

Capacity: indicates the maximum length of the string in the memory allocation

If the capacity is not enough, extra capacity will be allocated(usually doubled).

StringBuilder though has less method supported, but it has a ToString() method after the string is built.

For example,

// Create a StringBuilder

StringBuilder result = “far”;

result = result.Replace(‘f’, ‘c’);

result.Append(“go”);

// The above operation won’t create a new object if the capacity is large enough.

Console.WriteLine(result.ToString());

// cargo is printed