1. Lecture 6
C++ Strings
1
TCP1231 Computer Programming I
2. 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.
2
TCP1231 Computer Programming I
5. 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;
5
TCP1231 Computer Programming I
6. C++ String
Notes
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
6
TCP1231 Computer Programming I
7. 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"
7
TCP1231 Computer Programming I
8. #include <iostream>
#include <iomanip>
#include <string> Demonstrate
using namespace std;
int main () String
{
string s1;
string s2 ("Hello World");
Constructors
string s3 (s2);
string s4 (5, 'A');
string s5 (s2, 6);
string s6 ("Hello", 2);
string s7 ("Hello", 3, 2); Value of s1:
Value of s2: Hello World
cout << "Value of s1: " << s1 << endl;
Value of s3: Hello World
cout << "Value of s2: " << s2 << endl;
cout << "Value of s3: " << s3 << endl; Value of s4: AAAAA
cout << "Value of s4: " << s4 << endl; Value of s5: World
cout << "Value of s5: " << s5 << endl; Value of s6: He
cout << "Value of s6: " << s6 << endl; Value of s7: lo
cout << "Value of s7: " << s7 << endl;
return 0;
} // main
8
TCP1231 Computer Programming I
9. string class in C++ Standard Library
#include <iostream>
#include <string>
using namespace std;
int main() {
char cstr[] = "Hi";
string s1,s2;
string s3 = "hello"; must #include <string> and use namespace std
string s4("aloha");
string s5 = cstr; construct empty string
string s6(cstr);
construct a string based on c-String
string s7(s3); []
cout << "[" << s1 << "]" << endl; construct a
cout << "[" << s2 << "]" << endl;
string based on []
another string
cout << "[" << s3 << "]" << endl; [hello]
cout << "[" << s4 << "]" << endl; [aloha]
cout << "[" << s5 << "]" << endl;
cout << "[" << s6 << "]" << endl;
[Hi]
cout << "[" << s7 << "]" << endl; [Hi]
} [hello]
9
TCP1231 Computer Programming I
10. Assignment of Strings
Variables of type string can be assigned with
the = operator
Example: string s1, s2, s3;
…
s3 = s2;
Quoted strings are type cast to type string
Example: string s1 = "Hello Mom!";
10
TCP1231 Computer Programming I
11. When assigning string to a c++ string,
#include <iostream> we do not need to worry about whether
#include <string> there is enough memory allocated or
using namespace std;
not, the string will automatically adjust
int main() { its size if there is not enough memory
char cstr[] = "Arnold"; allocated.
string s1,s2,s3;
assigning c-string into c++ string
s1 = cstr;
s2 = "Schwarzenegger";
assigning a c++ string into another c++
s3 = s1;
string
cout << "[" << s1 << "]" << endl;
cout << "[" << s2 << "]" << endl; [Arnold]
cout << "[" << s3 << "]" << endl; [Schwarzenegger]
}
[Arnold]
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.
11
TCP1231 Computer Programming I
13. 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;
13
TCP1231 Computer Programming I
14. 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);
14
TCP1231 Computer Programming I
15. getline Example
This code demonstrates the use of getline with
string objects
string line;
cout "Enter a line of input:n";
getline(cin, line);
cout << line << "END OF OUTPUTn";
Output could be:
Enter some input:
Do be do to you!
Do be do to you!END OF OUTPUT
15
TCP1231 Computer Programming I
16. #include <iostream>
#include <string>
getline
similar to the cin.getline() function to read
using namespace std;
int main() {
characters into C-string from user,
string s; however, for the C++-string, the cin is one
of the parameter of the getline() function.
cout << "=> ";
cin >> s;
cin.ignore(1000,'n');
cout << s << endl;
cout << "=> ";
getline(cin, s);
=> how are you? i am fine
cout << s << endl; how
=> how are you? i am fine
cout << "=> ";
getline(cin, s, '?');
how are you? i am fine
cout << s << endl; => how are you? i am fine
} how are you
16
TCP1231 Computer Programming I
17. getline
#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; Enter Your Name in the form lastname,firstname:
} // main Azli, Fikri
Your Name is: Fikri Azli
17
TCP1231 Computer Programming I
18. More Examples
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <conio.c> #include <conio.c>
using namespace std; using namespace std;
int main () int main ()
{ {
cout << "Enter some words. n"; cout << "Enter some words. n";
string strIn; string strIn;
while (cin >> strIn) while (getline(cin, strIn))
cout << strIn << endl; cout << strIn << endl;
cout << “The End"; cout << “The End";
getch(); getch();
return 0; return 0;
} // main } // main
18
TCP1231 Computer Programming I
19. 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'
19
TCP1231 Computer Programming I
20. 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!
20
TCP1231 Computer Programming I
21. 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';
21
TCP1231 Computer Programming I
22. Member Function length
The string class member function length
returns
the number of characters in the string object:
Example:
int n = string_var.length( );
22
TCP1231 Computer Programming I
23. 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
23
TCP1231 Computer Programming I
24. #include <iostream>
#include <string>
using namespace std;
String
int main () {
string str1 ("ABC Company");
string str2 ("ABC");
Comparisons
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)
str1 > str2
cout << "str2 == str3" << endl; str2 == str3
return 0;
} // main 24
TCP1231 Computer Programming I
25. 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);
25
TCP1231 Computer Programming I
26. #include <iostream>
#include <string>
using namespace std;
String
int main () { Concatenation
string str1 = "This is ";
string str2 = "a string"; This is a string
string str3;
Begin append: This is a string
str3 = str1 + str2;
cout << str3 << endl; Append method: This is a string string
Append characters: This is a string!!!!!
cout << "nBegin append: ";
str1 = str1 + str2; We can add/concatenate C++
cout << str1 << endl; strings, C-strings or characters
into a C++ string to form a new
str1.append(str2, 1, string::npos); C++ string using the '+' operator
cout << "Append method: " << str1 << endl; without needing to use the
strcat() functions as in C-string.
str3.append(5, '!'); The strcat() function can only
cout << "Append characters: " << str3; be used with C-strings.
return 0;
}
26
TCP1231 Computer Programming I
27. String Extraction
Access the substring of the calling string
starting at position and having length
characters
Format
str.substr(position, length);
27
TCP1231 Computer Programming I
29. 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.
29
TCP1231 Computer Programming I
30. #include <iostream>
#include <string> Find
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;
"ten" at: 5
"tin" not at: -1
return 0;
}
Page 598
30
TCP1231 Computer Programming I
31. #include <iostream> Find
#include <string>
using namespace std; return the index of the first occurrence of string
int main() {
"be" within s1 starting from position 0.
string s1 = "...to be, or... not to
be!";
string s2 = "be"; return the index of the first occurrence of
string s3; string "be" within s1 starting from position 8.
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... not
}
6
6
6
23
31
TCP1231 Computer Programming I
32. #include <iostream>
#include <string>
Find
using namespace std;
returns the index of the
first instance in s1 of any
int main() { character in s2, starting
string s1 = "...to be, or... not to be!";
string s2 = "aeiou";
the search at position 11.
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;
}
4
17
returns the index of the first
3
instance in s1 of any character
15
NOT in s2, starting the search
at position 12.
32
TCP1231 Computer Programming I
33. 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);
33
TCP1231 Computer Programming I
34. #include <iostream>
#include <string>
using namespace std; Insertion
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 Test
} str1 ==>1: This is a Test
str1 ==>2: This is a Test, are you sure
str1 ==>3: This is a Test, are you sure???
TCP1231 Computer Programming I 34
35. 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
35
TCP1231 Computer Programming I
36. #include <iostream>
#include <string> Replacement
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 ==>0: My Name was Omar Ahmad
str1 ==>1: My Name is Omar Ahmad
str1.replace(15, 6, str2, 15, 9);
str1 ==>2: My Name is Omar Zaqaibeh
cout << "str1 ==>2: " << str1 << endl;
str1 ==>3: What is Your Name?
str1.replace(0, str1.length(), "What is Your Name?");
cout << "str1 ==>3: " << str1 << endl;
return 0;
}
36
TCP1231 Computer Programming I
37. #include <iostream>
#include <string>
using namespace std; Erase,
int main () {
string str1 = "This is one string";
string str3;
Clear, and
cout << "str1 ==>0: " << str1 << endl; Empty
str3 = str1;
str1.erase();
cout << "str1 ==>1: " << str1 << endl; str1 ==>0: This is one string
if (str1.empty()) str1 ==>1:
cout <<"ntstr1 is empty nn";
str1 = str3;
str1 is empty
str1.erase(8, 4);
cout << "str1 ==>2: " << str1 << endl;
str1 = str3; str1 ==>2: This is string
str1.clear(); str1 ==>3:
cout << "str1 ==>3: " << str1 << endl;
if (str1.empty()) str1 is empty
cout <<"ntstr1 is empty n";
return 0;
} 37
TCP1231 Computer Programming I
38. 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”
38
TCP1231 Computer Programming I
39. #include <iostream>
#include <string> Swap
#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); str1 ==>0: read then eat
cout << "str1 ==>1: " << str1 << endl;
str2 ==>0: eat then sleep
cout << "str2 ==>1: " << str2 << endl;
str1 ==>1: eat then sleep
return 0;
}
str2 ==>1: read then eat
39
TCP1231 Computer Programming I
40. string Objects to C-strings
Recall the automatic conversion from C-string
to 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);
40
TCP1231 Computer Programming I
41. 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
41
TCP1231 Computer Programming I
42. Conversion between C-string and C++ string
valid, assign a C-string to
char cstr[20] = "hello";
C++ string
string cppstr = "world";
cppstr = cstr;
Invalid, can not assign nor
cstr = cppstr; copy a C++-string to C
strcpy(cstr, cppstr); string.
strcpy(cstr, cppstr.c_str() );
valid, convert a C++-string to C
string (using the c_str()
cstr = cppstr.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.
42
TCP1231 Computer Programming I