Fabbri Systems Forum Index Fabbri Systems
Fabbri Systems Technical Forums
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

The C++ string Tutorial: Creating Strings

 
Post new topic   Reply to topic    Fabbri Systems Forum Index -> C++ for C Programmers

 

 

 

 

View previous topic :: View next topic  
Author Message
admin
Site Admin


Joined: 28 Feb 2006
Posts: 24

PostPosted: Fri Mar 10, 2006 7:36 pm    Post subject: The C++ string Tutorial: Creating Strings Reply with quote

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.
Back to top
View user's profile Send private message Send e-mail
Display posts from previous:   
Post new topic   Reply to topic    Fabbri Systems Forum Index -> C++ for C Programmers All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group