//------------------------------------------------- // // Examples of string handling // // Simon Parsons // April 18th 2007 // //------------------------------------------------- // Include C++ library definitions #include // For input and output #include // To handle strings using namespace std; int main() { // Variable definitions int countG = 0; string dna = "ggtataccggaatatagg"; // Note how we can define a string and string dna2 = "ttggaagg"; // Give it a value string::size_type len, pos; // This is the right data type for an // index into a string. // Printing a string cout << "Here we print the string dna" << endl; cout << dna << endl << endl; // Calculating the length of a string cout << "Now we give the length of dna in two ways" << endl; len = dna.length(); cout << len << endl; len = dna.size(); cout << len << endl << endl; // Another way to concatente two strings cout << "Next we concatenate two strings and print the result" << endl; dna2 += dna; cout << dna2 << endl << endl; // You can make an empty string cout << "We can make that string blank" << endl; dna2.clear(); cout << dna2 << endl; cout << "Do you want to see that again?" << endl << endl; // You can find a string within a string cout << "Where is tata in the string dna?" << endl; pos = dna.find("tata", 0); cout << pos << endl; cout << "Where does it occur the second time?" << endl; pos = dna.find("tata", pos + 1); cout << pos << endl << endl; // Or a character in a string cout << "Where is the first c?" << endl; pos = dna.find('c', 0); cout << pos << endl << endl; // npos is what you get if you can't find what you are looking for cout << "What if we look for the string dog?" << endl; pos = dna.find("dog", 0); cout << pos << endl; cout << "Eh?" << endl; cout << dna.npos << endl << endl; // That gives you a way to keep searching through a string until the end cout << "How many gs are there?" << endl; pos = dna.find('g',0); while (pos != dna.npos) { countG++; pos = dna.find('g', pos + 1); } cout << countG << endl << endl; // Replace text cout << "Replace 4 characters starting in position 2 with gaga" << endl; dna.replace(2, 4, "gaga"); cout << dna <