11.6 Strings with std::string

11.6 Strings with std::string

std::string is a class used to represent (encapsulate) a string data type, and it can be used like any other data type in C++. It is designed to solve the many problems that arise with standard string arrays using the char data type. std::string doesn't need to be declared as an array; instead, it is a single class that represents a string. Not only does it offer methods to calculate the length of a string, search a string, and other functions, but it can expand and shrink to match the exact length of a string. As characters are added to the string, it grows in size, and as characters are removed, it shrinks. In short, it does the hard work for you. Let's examine std::string further.

11.6.1 Creating std::string Objects

std::string is a class and is therefore a blueprint for objects. Thus, objects of class std::string can be created using either the traditional declaration or dynamic memory management. Both methods are shown below.

      std::string myString = "hello world";      //or      std::string *str = new std::string("hello"); 

11.6.2 Using Strings and the + Operator

Strings can be assigned to std::string objects in the same way numbers can be assigned to integer objects by using the assignment operator (MyString = “hello world\n”;). However, how do you add two strings? In the sense of numbers like 2+2, we know the answer to be 4, and we can do this in programming. We also know that adding two pointers together means adding their memory addresses. For example, consider the following array of numbers:

      int Numbers = {1,2,3,4,5,6}; 

If we then write Numbers+=1, it will be the equivalent of saying Numbers[1], which refers to the value of 2 since it is the second element in the array, with arrays starting at 0. But what can we say about “hello” + “world”? What we mean to do, of course, is to add together the two strings to make "hello world". Previously this was not a statement possible with arrays, but the std::string class thankfully offers such functionality. This means the following is possible:

      #include <iostream>      int main()      {         std::string str = "hello";         str = str + " world";         std::cout<<str; //Will now say "hello world"         return 0;      } 

11.6.3 String Methods

The std::string class offers valuable functionality because it can transparently encapsulate variable length strings, allow us to assign whole strings to the class (in the case of MyStr = “hello”), and add strings together using the addition operator. But std::string goes even further than this and offers even more methods to perform operations on strings. Some of these methods are discussed below. String Length

Given an arbitrary std::string object, we know that it may hold a string of potentially any length. That is, the string may contain any number of characters, from zero to as many as memory will allow. In the case of a simple string like "hello world", it is difficult to see why one would want to know how many characters a string contained. But the length of a string is valuable information, as later chapters will show. std::string therefore offers a method to return the length of a string. Not surprisingly, this method is called length.

      int length = str.length(); String Conversion

Using std::string is a good way of representing strings, but it is not without its problems. One of the most notable obstacles to those who use the std::string class is that there are a number of functions that accept strings using the old char[] array style. This means such functions are expecting to receive a string as an argument, and they expect the string to be structured into a standard char array, of the kind explained earlier. Naturally, if we pass a std::string object for this argument, the compiler will tell us there is a type mismatch because a std::string object is not the same as a char array. Thankfully, std::string offers the c_str method (convert string), which returns a char array that is identical to the string represented by the std::string object.

      const char *array_string = str.c_str(); Inserting Characters

We know that it would have required a tedious amount of work to use a char array to store variable length strings, and that it would have been even worse to add extra strings to the start and end of that array. It is even more troublesome to imagine how exactly we might have programmed an array to accepted newly inserted characters at specific positions within the string, such as adding a new letter in the middle of the string (for instance, the letter "a" between "hello" and "world"). Not only would this mean the length of the string would have increased by an extra character, but all the characters after the inserted letter would need to shuffle along by one space to make room for the new character. Again, std::string comes to the rescue and provides a method to do just this. It works as follows: Each character-such as "h"-in the string has an index, which is a number that refers to its position within the string. It's the same as an array index. The first character is at 0, the next at 1, the next at 2, and so on. Characters can be inserted at any point in the string using the insert method. This method inserts a new string of any size into the current string at the specified index. It requires two arguments: an integer to specify the index where the new string is to be inserted and the actual string to insert.

      string str = "0123";      str.insert (1,"XYZ");      cout<<str1; // "0XYZ123" Substrings

A substring is a smaller part of a string. "hello" and "world" are both substrings of "hello world". "hel" and "orl" are also both substrings of "hello world" since each is included in the larger "hello world" string. The std::string class offers the substr method to return a new std::string object that is the specified substring. This method accepts two arguments: an index within the string where the substring is to begin and the number of characters from this point.

      std::string s("this is a test string");      std::string sub = s.substr(3,5); Erase

Naturally, a whole string can be cleared using a simple assignment of MyString=“”;. But it is also possible to remove specific sections of a string, effectively cutting out whole substrings. This can be achieved using the erase method of std::string. The arguments of erase accept the index where erasing should begin and the number of characters from this point that should be removed.

      string str = "abcdefghi";      str.erase (5,3);      cout<<str; // "abcdei" Replace

Beyond creating std::string objects based on substrings of an original string, it is also possible to replace existing characters in a string, much like someone would overwrite text in a word processor. This process is really a combination of erase and insert, where a number of existing characters are removed from a specified index, and then new characters are inserted at the same index. This is accomplished with by the single method of replace. It replaces the characters beginning at a specified index with a specified substring.

      string str1 = "abcdefghi";      string str2 = "XYZ";      str1.replace (4,2,str2);      cout<<str1; // "abcdXYZghi" 

Introduction to Game Programming with C++
Introduction to Game Programming with C++ (Wordware Game Developers Library)
ISBN: 1598220322
EAN: 2147483647
Year: 2007
Pages: 225
Authors: Alan Thorn

Similar book on Amazon
Beginning C++ Through Game Programming
Beginning C++ Through Game Programming
Beginning Game Programming
Beginning Game Programming
The Ultimate Guide to Video Game Writing and Design
The Ultimate Guide to Video Game Writing and Design

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