Topic : STL I: String and String Streams
Author : Eric Sanchez
Page : 1

C++'s STL I: String and String Streams


This article was contributed by Eric Sanchez
Environment: C++

So you are done learning the basics of C++ and might wonder what's next or if Java is more powerful, for it has so many more useful built-in functions? The truth is that most books and courses only cover the surface of C++. In part I of this series of tutorials, we will explore strings and string streams. Prior experience with the fundamentals of C++ is a must.

ANSI C++ recently adopted STL, the Standard Template Library. This library contains an impressive assortment of versatile functions and objects. The code presented here has been tested with Visual C++ 6.0 but should be applicable to most recent compilers.

The nucleus of STL is the separation of objects and structures from the functions. As a result, most functions are generic and can be used with most data structures. In order to accomplish this, the library does not employ OOP but rather uses templates.

Start...
As usual, before beginning any program, we must include the header files. The main difference from the old C++ is that when using STL, the file does not end with a .h.
For example,
#include <iostream.h> would be written as #include <iostream>. There are many other cases that are not as simple, yet they’re trivial. For example, math.h won’t work if included as math. Instead, you have to include cmath. This is the same for time.h, which must is ctime, stdlib.h, as cstdlib, time.h, as ctime, among others. This alone will not be sufficient. You have to specify that you would like to use the std namespace. There are two ways of doing this:

1. Insert std:: before every function. Example: std::cout<<”Hello maxcode”;
2. Type: using namespace std; before using the functions, usually after all the header files.

Now we are ready to start. Here’s what a simple sample might look like:

#include <iostream>
#include <cctype>
using namespace std;
void main(){

         cout<<"Do you like Maxcode: (Y,N): ";
         char ans;
         cin>>ans;
         if (toupper(ans)=='Y')cout<<"Cool\n";
         else cout<<"Shame on you :(\n";
}


Strings
In C\C++, many people use arrays of char to create strings, such as char demo[10]; There’s a better solution to this by using the standard string. You must include <string> before using them. They have many advantages over the chars. For instance, they contain a series of member functions, they can be resized dynamically, many algorithms can be applied to it, and so on.
There are two main ways to declare the string. The first one is: string variablename; You can also specify an a char string as a parameter. Ex:

string demo;string demo1=”Hello there”;char old[] = “Hello”;string demo3(old); //Demo3 will be initialized to Hello
Here’s a few useful string member functions:

1. length() - Returns the number of character in the string


2. find: there are 4 prototypes. It returns the position of a given character or string.
Ex: int pos = demo3.find(“ll”); //Would return 2
Ex: int pos = demo3.find(“lo”,2); //Find lo. Start searching at position 2


3. substr(pos1, count) - It substrings a string.
Ex: string d = demo3.substr(1,3); //Would return ello, start at position 1 and get 3 char.


4. erase(pos, count) - Erases a sequence of characters starting at pos.
Ex: demo3.erase(1,3); //Erase ell (Starts at 1 and erase 3 chars). demo3 will then be Ho.


5. insert - It has 8 prototypes. It basically inserts a series of characters into the string at a specified position.
Ex: demo3.insert(2, "HeHe"); //demo3 will them be HeHeHello. It inserted HeHe starting at position 2.


6. max_size() - Return the maximum size the string can be.


7. resize (length) - Resizes the string to a given length.
resize(length, char) - Resizes the string and fills the empty space with the char.
Ex: demo3.resize(122, ‘*’);


8. c_str() - returns the char array. Needed if you need to use char* or char[]...

That is only a few of its many functions.
There are other benefits. For example, you can concatenate strings using +. Ex: demo3 = demo3+” “+demo1;. In addition, you can compare strings using ==. Ex: if (demo1==demo3) cout<<”Hmm.. strange”; This is much better than using strcmp.

String Streams
Another useful feature is the ability to use subscripts, justt as in arrays. Ex: demo3[2]=’A’; cout<<demo3[1]; A warning about this though, there will be an error if you use indexes on a place that does not contain any value.
For instance, this will not work:
string d;
d[0] =’A’;

However, it will if you use string d = “ “ or d+='A' or use the resize member function.

Speaking of strings, there is a great class to manipulate them. It allows you to convert integers, floats, etc to strings and extract them from them.
In order to use it, you must include <sstream>. Now just like there are ifstream and ofstream for file handling, you can use istringstream and ostringstream. Then you’ll be able to use strings in a very similar way to files.
Let’s begin by creating a simple string that represents a coordinate (x , y).
string coord = “(12, 102)”;

Now we would like to read the value of x and store it in an int variable and the same for the y.
To read the numbers, it would be easier to do it sequentially. As a result, we need a variable to read ( and ,. Then we simply use >> to extract the values into the variables:

istringstream in(coord); char p;int x,y;in>>p>>x>>p>>y;

We could have done the above by using strtok or sscanf but this way, it is usually easier.

Now x will have the value 12 and y 102. It would be similar if we want to extract floats, strings, longs, etc. Note that space is not counted when reading by default, unless you specifically change it. There are many other options such as in.setf(..), etc.
What about if you want to do the opposite, create a string from the values? In this case, we would use ostringstream and <<.

int x=12,y=102;ostringstream out;out<<"("<<x<<" , "<<y<<")";string coord = out.str(); //We must use str() to return the resulting string.

Well, that’s it for now. In part II I’ll go into more advanced subjects such as vectors, maps, and lists. Then part III will be mostly on algorithms performed on these containers, such as sort() and count().
Have Fun!


Page : 1