The STL String Class - Checks, find, concatenation
(Page 3 of 4 )
Checking to see if it contains any data can be done via two methods. The member function empty() will return a bool value, or you can also make a comparison with an empty string as follows.
if(text == "")
if(text.empty())
Either of these will have the same result. With this, we have reached the problem of comparing two strings. The member function responsible for this is the compare(). Nevertheless, calling the operator == will call the comparison if the items can be cast on both sides or already are strings. The < and > operators are defined and will return which one is smaller by comparing the ASCI chars each after the other until it finds one smaller than the char at the same place in the other. Both examples below will return a true or false.
string text, beta;
text.compare(beta);
text == "Yeti"; // here a string type will be created from the
//"Yeti" (char*) and after that called the comparison function
Concatenation of two streams is readable by doing it only with the addition operator, but you can insert a new string into a old one at any place given by the vastly different types of definition of the insert member function. Here is, for example, the concatenation in three ways. However, during the insert operation, the alfa will be extended to the concentration, but this can be changed by first assigning alfa to both, and then inserting beta into both.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string alfa = "alfa ";
string beta = "beta";
string both;
cout << (both = alfa + beta) << endl;
both = alfa;
both.insert(both.end(), beta.begin(), beta.end());
cout << both << endl;
cout << (both = alfa.insert(alfa.length(), beta)) << endl;
return 1;
}
alfa beta
alfa beta
alfa beta
Press any key to continue . . .
Finding a string inside of another is always a hard task for newbie coders. Especially if they have a good knowledge of C, most people are searching for absurdly complicated names (strstr for example in C). The find functions does exactly what its name says; it searches the argument string and returns the position at where it finds it, or string::npos if it is not found.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string alfa = "nalfa ";
string beta = "alf";
cout << alfa.find(beta) << endl;
return 1;
}
1
Press any key to continue . . .
Of course, the list of finding methods is much larger, as the picture below indicates:

Next: Approaching the end >>
More C++ Articles
More By Gabor Bernat