admin Site Admin
Joined: 28 Feb 2006 Posts: 24
|
Posted: Fri Mar 10, 2006 7:36 pm Post subject: The C++ string Tutorial: Creating Strings |
|
|
This tutorial is a work in progress.
In C, a string has the type char *. Thus the variable char *p is a pointer to a region of memory containing characters, ending will a zero (null) value.
C++ introduces a class string which aims to provide a higher-level interface for manipulating strings. This tutorial shows examples of common string operations first in C, and then in C++. I write much more C code so correct me if there is a better way to do things in C++.
Allocate a new string in C
| Code: |
{
char *stack_str = "jack";
char *heap_str;
heap_str = (char *)malloc((MAX_STR_LEN + 1));
sprintf(heap_str, "beep beep!");
printf( "stack_str '%s', heap_str '%s'\n", stack_str, heap_str);
}
|
Allocate a new string in C++
| Code: |
{
// Allocate space for MAX_STR_LEN on the heap
string cpp_string(MAX_STR_LEN, '\0');
// This string should fit in the original object
cpp_string = "woo, yay";
cout << "cpp_string '" << cpp_string << "'\n";
// C++ strings handle allocation details for you
// The string will be reallocated, again from the heap.
cpp_string = "This string is more than fifteen characters";
}
|
Notice that in the C++ code, we did not explicitly malloc() or free() the space that the string is stored in. C++'s std::string class handles allocation behind the scenes when the object is created (via the constructor). In this example, the automatic variable cpp_string is cleaned up when it's destructor is called as it goes out of scope. |
|