Lab # 9 String
Lab # 9 String
Lab Objectives
The objectives of this lab are to demonstrate.
1. String Class
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1(“Man”); //initialize
string s2 = “Beast”; //initialize
string s3;
s3 = s1; //assign
cout << “s3 = “ << s3 << endl;
s3 = “Neither “ + s1 + “ nor “; //concatenate
s3 += s2; //concatenate
cout << “s3 = “ << s3 << endl;
s1.swap(s2);
cout << s1 << “ nor “ << s2 << endl;
return 0;
}
s3 = Man
s3 = Neither Man nor Beast
Beast nor Man
Finding string Objects
The string class includes a variety of member functions for finding strings and substrings in
string objects.
Found Kubla at 14
First of spde at 7
First consonent at 1
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1(“Quick! Send for Count Graystone.”);
string s2(“Lord”);
string s3(“Don’t “);
s1.erase(0, 7); //remove “Quick! “
s1.replace(9, 5, s2); //replace “Count” with “Lord”
s1.replace(0, 1, “s”); //replace ‘S’ with ‘s’
s1.insert(0, s3); //insert “Don’t “ at beginning
s1.erase(s1.size()-1, 1); //remove ‘.’
s1.append(3, ‘!’); //append “!!!”
int x = s1.find(‘ ‘); //find a space
while( x < s1.size() ) //loop while spaces remain
{
s1.replace(x, 1, “/”); //replace with slash
x = s1.find(‘ ‘); //find next space
}
cout << “s1: “ << s1 << endl;
return 0;
}
s1: Don’t/send/for/Lord/Graystone!!!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string aName = “George”;
string userName;
cout << “Enter your first name: “;
cin >> userName;
if(userName==aName) //operator ==
cout << “Greetings, George\n”;
else if(userName < aName) //operator <
cout << “You come before George\n”;
else
cout << “You come after George\n”;
//compare() function
int n = userName.compare(0, 2, aName, 0, 2);
cout << “The first two letters of your name “;
if(n==0)
cout << “match “;
else if(n < 0)
cout << “come before “;
else
cout << “come after “;
cout << aName.substr(0, 2) << endl;
return 0;
}