computer programming- lecture 6
DESCRIPTION
C++ StringsTRANSCRIPT
1TCP1231 Computer Programming I
Lecture 6C++ Strings
2TCP1231 Computer Programming I
Objectives
Understand the basic types of strings. Define and use the string class and C-type
strings. Read and write strings. Access and manipulate characters or sub-
strings within a string. Concatenate and compare strings. Insert, replace, swap, or erase a sub-string in
a string.
3TCP1231 Computer Programming I
String Taxonomy
4TCP1231 Computer Programming I
String Formats
5TCP1231 Computer Programming I
The Standard string Class
The string class allows the programmer to treat strings as a basic data type No need to deal with the implementation as with
C-strings The string class is defined in the string library
and the names are in the standard namespace To use the string class you need these lines:
#include <string> using namespace std;
6TCP1231 Computer Programming I
Notes
C++ String
The extraction operator stops at whitespace. To read a string with spaces, we must use getline. The string input /output operators and functions are
defined in the string header file, not the I/O stream header file
7TCP1231 Computer Programming I
string Constructors
The default string constructor initializes the string to the empty string
Another string constructor takes a C-string argument Example:
string phrase; // empty string string noun("ants"); // a string version // of "ants"
8TCP1231 Computer Programming I
#include <iostream>#include <iomanip>#include <string>using namespace std;int main (){
string s1;string s2 ("Hello World");string s3 (s2);string s4 (5, 'A');string s5 (s2, 6);string s6 ("Hello", 2);string s7 ("Hello", 3, 2);
cout << "Value of s1: " << s1 << endl;cout << "Value of s2: " << s2 << endl;cout << "Value of s3: " << s3 << endl;cout << "Value of s4: " << s4 << endl;cout << "Value of s5: " << s5 << endl;cout << "Value of s6: " << s6 << endl;cout << "Value of s7: " << s7 << endl;return 0;
} // main
Value of s1: Value of s2: Hello WorldValue of s3: Hello WorldValue of s4: AAAAAValue of s5: WorldValue of s6: HeValue of s7: lo
Demonstrate String Constructors
9TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;int main() { char cstr[] = "Hi"; string s1,s2;
string s3 = "hello"; string s4("aloha"); string s5 = cstr; string s6(cstr);
string s7(s3); cout << "[" << s1 << "]" << endl; cout << "[" << s2 << "]" << endl; cout << "[" << s3 << "]" << endl; cout << "[" << s4 << "]" << endl; cout << "[" << s5 << "]" << endl; cout << "[" << s6 << "]" << endl; cout << "[" << s7 << "]" << endl;}
[][][hello][aloha][Hi][Hi][hello]
construct a string based on c-String
construct empty string
construct a string based on another string
must #include <string> and use namespace std
string class in C++ Standard Library
10TCP1231 Computer Programming I
Assignment of Strings
Variables of type string can be assigned withthe = operator Example: string s1, s2, s3;
… s3 = s2;
Quoted strings are type cast to type string Example: string s1 = "Hello Mom!";
11TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;
int main() { char cstr[] = "Arnold"; string s1,s2,s3; s1 = cstr; s2 = "Schwarzenegger"; s3 = s1; cout << "[" << s1 << "]" << endl; cout << "[" << s2 << "]" << endl; cout << "[" << s3 << "]" << endl;}
[Arnold][Schwarzenegger][Arnold]
assigning c-string into c++ string
assigning a c++ string into another c++ string
When assigning string to a c++ string, we do not need to worry about whether there is enough memory allocated or not, the string will automatically adjust its size if there is not enough memory allocated.
We can assign a C-strings or C++ strings directly into a C++ string without needing to use the strcpy() functions as in C-string. The strcpy() function can only be used with C-strings.
12TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;
int main () {
string str1 ("String 1");string str2; string str3;string str4;string str5 = "String 5";
cout << "String 1: " << str1 << endl;str2 = str1;cout << "String 2: " << str2 << endl;str3 = "Hello";cout << "String 3: " << str3 << endl;str4 = 'A';cout << "String 4: " << str4 << endl;cout << "String 5: " << str5 << endl;return 0;
} // main
String Assignment
String 1: String 1String 2: String 1String 3: HelloString 4: AString 5: String 5
13TCP1231 Computer Programming I
I/O With Class string
The insertion operator << is used to output objects of type string Example: string s = "Hello Mom!";
cout << s; The extraction operator >> can be used to
input data for objects of type string Example: string s1;
cin >> s1;
14TCP1231 Computer Programming I
getline and Type string
A getline function exists to read entire lines into a string variable This version of getline is not a member of the
istream class, it is a non-member function Syntax for using this getline is different than that
used with cin: cin.getline(…) Syntax for using getline with string objects:
getline(Istream_Object, String_Object);
15TCP1231 Computer Programming I
getline Example
This code demonstrates the use of getline withstring objects string line;
cout "Enter a line of input:\n";getline(cin, line);cout << line << "END OF OUTPUT\n";
Output could be: Enter some input: Do be do to you! Do be do to you!END OF OUTPUT
16TCP1231 Computer Programming I
#include <iostream>#include <string>
using namespace std;int main() { string s;
cout << "=> "; cin >> s; cin.ignore(1000,'\n'); cout << s << endl; cout << "=> "; getline(cin, s); cout << s << endl; cout << "=> "; getline(cin, s, '?'); cout << s << endl;}
=> how are you? i am finehow=> how are you? i am finehow are you? i am fine=> how are you? i am finehow are you
similar to the cin.getline() function to read characters into C-string from user, however, for the C++-string, the cin is one of the parameter of the getline() function.
getline
17TCP1231 Computer Programming I
#include <iostream>#include <iomanip>#include <string>#include <conio.c>using namespace std;
int main (){
cout << "Enter Your Name in the form lastname,firstname: ";string lName; string fName;getline (cin, lName, ','); getline (cin, fName);
cout << "Your Name is: " << fName << " " << lName; getch();
return 0;} // main
Enter Your Name in the form lastname,firstname: Azli, FikriYour Name is: Fikri Azli
getline
18TCP1231 Computer Programming I
#include <iostream>#include <string>#include <conio.c>using namespace std;
int main (){ cout << "Enter some words. \n"; string strIn; while (cin >> strIn) cout << strIn << endl; cout << “The End"; getch(); return 0;} // main
#include <iostream>#include <string>#include <conio.c>using namespace std;
int main (){ cout << "Enter some words. \n"; string strIn; while (getline(cin, strIn)) cout << strIn << endl; cout << “The End"; getch(); return 0;} // main
More Examples
19TCP1231 Computer Programming I
ignore
ignore is a member of the istream class ignore can be used to read and discard all the
characters, including '\n' that remain in a line Ignore takes two arguments
First, the maximum number of characters to discard Second, the character that stops reading and
discarding Example: cin.ignore(1000, '\n');
reads up to 1000 characters or to '\n'
20TCP1231 Computer Programming I
String Processing
The string class allows the same operations we used with C-strings…and more Characters in a string object can be accessed as
if they are in an array last_name[i] provides access to a single character
as in an array Index values are not checked for validity!
21TCP1231 Computer Programming I
Member Function at
at is an alternative to using [ ]'s to access characters in a string. at checks for valid index values Example: string str("Mary");
cout << str[6] << endl; cout << str.at(6) << endl;
str[2] = 'X'; str.at(2) = 'X';
22TCP1231 Computer Programming I
Member Function length
The string class member function length returns the number of characters in the string object:
Example: int n = string_var.length( );
23TCP1231 Computer Programming I
Comparison of strings
Comparison operators work with string objects Objects are compared using lexicographic order
(Alphabetical ordering using the order of symbols in the ASCII character set.)
= = returns true if two string objects contain the same characters in the same order Remember strcmp for C-strings?
<, >, <=, >= can be used to compare string objects
24TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;
int main () { string str1 ("ABC Company"); string str2 ("ABC"); string str3 ("ABC");
if (str1 == str2) cout << "str1 == str2" << endl;
if (str1 > str2) cout << "str1 > str2" << endl;
if (str1 < str2) cout << "str1 < str2" << endl;
if (str2 == str3) cout << "str2 == str3" << endl;
return 0;
} // main
str1 > str2str2 == str3
String Comparisons
25TCP1231 Computer Programming I
Using + With strings (Concatenation)
Variables of type string can be concatenated with the + operator Example: string s1, s2, s3;
… s3 = s1 + s2;
If s3 is not large enough to contain s1 + s2, more space is allocated
More specific, use append: append(string &str, size_t offset, size_t count); append(string &str); append(size_t count, char ch);
26TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;
int main () {string str1 = "This is "; string str2 = "a string";string str3;
str3 = str1 + str2;cout << str3 << endl;
cout << "\nBegin append: ";str1 = str1 + str2;cout << str1 << endl;
str1.append(str2, 1, string::npos);cout << "Append method: " << str1 << endl;
str3.append(5, '!');cout << "Append characters: " << str3;return 0;
}
This is a string
Begin append: This is a stringAppend method: This is a string stringAppend characters: This is a string!!!!!
String Concatenation
We can add/concatenate C++ strings, C-strings or characters into a C++ string to form a new C++ string using the '+' operator without needing to use the strcat() functions as in C-string. The strcat() function can only be used with C-strings.
27TCP1231 Computer Programming I
String Extraction
Access the substring of the calling string starting at position and having length characters
Format str.substr(position, length);
28TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;
int main () {string str1 = "Concatenation";string str2;
cout << "str1 contains: " << str1 << endl;cout << "str2 contains: " << str2 << endl;cout << “\t 0123456789012" << endl;
str2 = str1.substr();cout << "str2 ==> 1: " << str2 << endl;
str2 = str1.substr(5, 3);cout << "str2 ==> 2: " << str2 << endl;
str2 = str1.substr(5);cout << "str2 ==> 3: " << str2 << endl;return 0;
}
str1 contains: Concatenationstr2 contains: 0123456789012
str2 ==> 1: Concatenationstr2 ==> 2: tenstr2 ==> 3: tenation
String Extraction
29TCP1231 Computer Programming I
Find string Format
str.find(str1); returns index of the first occurrence of str1 in str
str.find(str1, pos);returns index of the first occurrence of
string str1 in str, the search starts at position pos.
str.find_first_of(str1, pos);returns index of the first instance in str of any character in str1, starting the search at position pos.
str.find_first_not_of(str1, pos);returns index of the first instance in str of any character not in str1, starting the
search at position pos.
30TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;
int main (){
int where; string str1 = "ccccatenatttt";
where = str1.find("ten");cout << "\"ten\" at: " << where << endl;
where = str1.find("tin");if (where != string::npos) cout << "\"tin\" at: " << where << endl;else cout << "\"tin\" not at: " << where << endl;
return 0;}
"ten" at: 5"tin" not at: -1
Find
Page 598
31TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;
int main() { string s1 = "...to be, or... not to
be!"; string s2 = "be"; string s3; s3 = s1.substr(6,13); cout << s3 << endl; cout << s1.find(s2) << endl; cout << s1.find("be") << endl; cout << s1.find("be",0) << endl; cout << s1.find("be",8) << endl;
return 0; }
be, or... not66623
return the index of the first occurrence of string "be" within s1 starting from position 0.
return the index of the first occurrence of string "be" within s1 starting from position 8.
Find
32TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;
int main() { string s1 = "...to be, or... not to be!"; string s2 = "aeiou"; string s3 = ",.!";
cout << s1.find_first_of(s2,0) << endl; cout << s1.find_first_of(s2,11) << endl;
cout << s1.find_first_not_of(s3,0) << endl; cout << s1.find_first_not_of(s3,12) << endl;}
417315
returns the index of the first instance in s1 of any character in s2, starting the search at position 11.
returns the index of the first instance in s1 of any character NOT in s2, starting the search at position 12.
Find
33TCP1231 Computer Programming I
Insert string
Inserts str2 into str beginning at position pos.str.insert(pos, str2);
Inserts str2, beginning at position start of length length, into str beginning at position pos.
str.insert(pos, str2, start, length);
34TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;
int main (){
string str1 = "This is Test";string str2 = "tell me if, are you sure";cout << "str1 ==>0: " << str1 << endl;
str1.insert(8, "a ");cout << "str1 ==>1: " << str1 << endl;
str1.insert(14, str2, 10, 14);cout << "str1 ==>2: " << str1 << endl;
str1 = str1.insert(str1.length(), 3, '?');cout << "str1 ==>3: " << str1 << endl;
return 0;}
str1 ==>0: This is Teststr1 ==>1: This is a Teststr1 ==>2: This is a Test, are you surestr1 ==>3: This is a Test, are you sure???
Insertion
35TCP1231 Computer Programming I
Replace the string
str1.replace(pos, len, str2);replace the str1 with str2 beginning at position pos of length len
str1.replace(pos, len, str2, start, length);replace the str1, beginning at position pos of length len, with str2 beginning at
position start of length length
36TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;
int main () { string str1 = "My Name was Omar Ahmad"; string str2 = "My Last Name is Zaqaibeh";
cout << "str1 ==>0: " << str1 << endl;
str1.replace(8, 3, "is"); cout << "str1 ==>1: " << str1 << endl;
str1.replace(15, 6, str2, 15, 9); cout << "str1 ==>2: " << str1 << endl;
str1.replace(0, str1.length(), "What is Your Name?"); cout << "str1 ==>3: " << str1 << endl; return 0;}
str1 ==>0: My Name was Omar Ahmadstr1 ==>1: My Name is Omar Ahmadstr1 ==>2: My Name is Omar Zaqaibehstr1 ==>3: What is Your Name?
Replacement
37TCP1231 Computer Programming I
#include <iostream>#include <string>using namespace std;int main () { string str1 = "This is one string";
string str3;
cout << "str1 ==>0: " << str1 << endl;str3 = str1;str1.erase();cout << "str1 ==>1: " << str1 << endl;if (str1.empty())
cout <<"\n\tstr1 is empty \n\n";str1 = str3;str1.erase(8, 4);cout << "str1 ==>2: " << str1 << endl;str1 = str3;str1.clear();cout << "str1 ==>3: " << str1 << endl;if (str1.empty())
cout <<"\n\tstr1 is empty \n";return 0;
}
str1 ==>0: This is one stringstr1 ==>1:
str1 is empty
str1 ==>2: This is stringstr1 ==>3:
str1 is empty
Erase, Clear, andEmpty
38TCP1231 Computer Programming I
Swap the two strings
swap(str1, str2);interchange the string str1 with str2
Example: Before swapping
str1 = “Multimedia” str2 = “University” After swapping
str1 = “University” str2 = “Multimedia”
39TCP1231 Computer Programming I
#include <iostream>#include <string>#include <conio.c>using namespace std;
int main (){ string str1 = "read then eat";
string str2 = "eat then sleep";
cout << "str1 ==>0: " << str1 << endl;cout << "str2 ==>0: " << str2 << endl;
cout << endl;swap(str1, str2);
cout << "str1 ==>1: " << str1 << endl;cout << "str2 ==>1: " << str2 << endl;
return 0;}
str1 ==>0: read then eatstr2 ==>0: eat then sleep
str1 ==>1: eat then sleepstr2 ==>1: read then eat
Swap
40TCP1231 Computer Programming I
string Objects to C-strings
Recall the automatic conversion from C-stringto string: char a_c_string[] = "C-string"; string_variable = a_c_string;
strings are not converted to C-strings Both of these statements are illegal:
a_c_string = string_variable; strcpy(a_c_string, string_variable);
41TCP1231 Computer Programming I
Converting strings to C-strings
The string class member function c_str returns the C-string version of a string object Example:
strcpy(a_c_string, string_variable.c_str( ) );
This line is still illegal a_c_string = string_variable.c_str( ); Recall that operator = does not work with C-
strings
42TCP1231 Computer Programming I
Conversion between C-string and C++ string
char cstr[20] = "hello"; string cppstr = "world";
cppstr = cstr;
cstr = cppstr; strcpy(cstr, cppstr);
strcpy(cstr, cppstr.c_str() );
cstr = cppstr.c_str() ;
valid, assign a C-string to C++ string
Invalid, can not assign nor copy a C++-string to C string.
valid, convert a C++-string to C string (using the c_str() function) before it is being copy into the C-string
Invalid, even though the C++-string has been convert to C-string, we can not assign the new C-string into another C-string, we need to use the strcpy() for that.
43TCP1231 Computer Programming I
The End