To use String class, you should first refer to a sample program "example_String.cpp" given in Appendix A and the String class which is given in Appendix A.
The 'String class' is a complete replacement for char and char * datatype. You can use 'String class' just like char and get much more functionalities. You should link with the library 'libString.a' which you can build from the makefile given in Appendix A and copy the library to /usr/lib or /lib directory where all the "C++" libraries are located. To use the 'libString.a' compile your programs like -
g++ example.cpp -lString
String aa; aa = "Creating an Universe is very easy, similar to creating a baby human."; // You can use aa.val() like a 'char *' variable in programs for (unsigned long tmpii = 0; tmpii < aa.length(); tmpii++) { //fprintf(stdout, "aa.val()[%ld]=%c ", tmpii, aa.val()[tmpii]); fprintf(stdout, "aa[%ld]=%c ", tmpii, aa[tmpii]); } // Using pointers on 'char *' val ... for (char *tmpcc = aa.val(); *tmpcc != 0; tmpcc++) { fprintf(stdout, "aa.val()=%c ", *tmpcc); }
The 'String class' provides these operators :-
String aa; String bb("Bill Clinton"); aa = "put some value string"; // assignment operator aa += "add some more"; // Add to itself and assign operator aa = "My name is" + " Alavoor Vasudevan "; // string cat operator if (bb == "Bill Clinton") // boolean equal to operator cout << "bb is equal to 'Bill Clinton' " << endl; if (bb != "Al Gore") // boolean 'not equal' to operator cout << "bb is not equal to 'Al Gore'" << endl;
The functions provided by String class has the same name as that of Java language's String class. The function names and the behaviour is exactly same as that of Java's String class. StringBuffer class is also provided. This will facilitate portability of code between Java and C++ (you can cut and paste and do minimum changes to code). The code from Java's function body can be copied into C++ member function body and with very mininum changes the code will compile under C++. Another advantage is that developers coding in both Java and C++ do not need to remember two different syntax or function names.
For example to convert integer to string do -
String aa; aa = 34; // The '=' operator will convert int to string cout << "The value of aa is : " << aa.val() << endl; aa = 234.878; // The '=' operator will convert float to string cout << "The value of aa is : " << aa.val() << endl; aa = 34 + 234.878; cout << "The value of aa is : " << aa.val() << endl; // The output aa will be '268.878' // You must cast String to convert aa = (String) 34 + " Can create infinite number of universes!! " + 234.878; cout << "The value of aa is : " << aa.val() << endl; // The output aa will be '34 Can create infinite number of universes!! 234.878'
Refer to Appendix A String.h for details about the String class function names. The same file String.h is reproduced here in next section.