Strings
Strings
Types of Strings
1. String Literals:
“Hello World”
“xyz 123 *&^#$!”
2. C-style strings:
char s[20];
2
literalString.cpp
...
int main()
{
char s[] = "Hello World";
3
literalString.cpp
...
char s[] = "Hello World";
> literalString.exe
Hello World
H,e,l,l,o, ,W,o,r,l,d,
4
Literal String
• To create a variable containing a literal string:
char s[] = “Hello World”;
5
ascii.cpp
...
int main()
{
char s[] = "Hello World";
return 0;
}
6
...
char s[] = "Hello World";
> ascii.exe
Hello World
H, e, l, l, o, , W, o, r, l, d,
72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100,
>
7
null Character
• Literal strings end in a null character: ‘\0’.
(Character ‘\0’ has ASCII code 0.)
char s[] = “Hello World”;
8
literalString2.cpp
...
int i;
char s[] = "Hello World";
i = 0;
while(s[i] != '\0')
{
cout << s[i] << ",";
i++;
}
cout << endl;
cout << "s[" << i << "] = " << int(s[i]) << endl;
...
9
literalString2.cpp
cout << s << endl;
i = 0;
while(s[i] != '\0')
{
cout << s[i] << ",";
i++;
}
cout << endl;
cout << "s[" << i << "] = " << int(s[i]) << endl;
> literalString2.exe
Hello World
H,e,l,l,o, ,W,o,r,l,d,
s[11] = 0
10
ascii2.cpp
...
i = 0;
while(s[i] != '\0')
{
cout << setw(4) << s[i] << ",";
i++;
}
cout << endl;
i = 0;
while(s[i] != '\0')
{
cout << setw(4) << int(s[i]) << ",";
i++;
}
cout << setw(4) << int(s[i]);
cout << endl;
...
11
...
i = 0;
while(s[i] != '\0')
{
cout << setw(4) << int(s[i]) << ",";
i++;
}
cout << setw(4) << int(s[i]);
cout << endl;
...
> ascii2.exe
Hello World
H, e, l, l, o, , W, o, r, l, d,
72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 0
>
12
C-style strings
• A C-style string is stored in an array of char;
• C-style strings should always end in ‘\0’;
13
cString.cpp
const int MAX_LENGTH(20);
// C-style strings should always end in '\0'
char s[MAX_LENGTH] =
{ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'};
s[1] = 'o';
s[2] = 'w';
s[3] = 'd';
s[4] = 'y';
cout << "String = " << s << endl;
s[5] = '\0';
cout << "String = " << s << endl;
14
cString.cpp
const int MAX_LENGTH(20);
// C-style strings should always end in '\0'
char s[MAX_LENGTH] =
{ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'};
cout << "String = " << s << endl;
s[1] = 'o';
s[2] = 'w';
s[3] = 'd';
s[4] = 'y';
cout << "String = " << s << endl;
s[5] = '\0';
cout << "String = " << s << endl;
> cString.exe
String = Hello World
String = Howdy World
String = Howdy
15
Literal String
• A literal string variable cannot be changed, i.e., the
following will generate a syntax error:
16
Capitalize
Change all characters in a string to capitals.
17
ASCII Code
Code Char Code Char Code Char Code Char
32 Space 48 0 65 A 97 a
33 ! 49 1 66 B 98 b
34 " 50 2 67 C 99 c
35 # 51 3 68 D 100 d
36 $ 52 4 69 E 101 e
37 % 53 5 70 F 102 f
38 & 54 6 71 G 103 g
39 ' 55 7 72 H 104 h
40 ( 56 8 73 I 105 i
41 ) 57 9 74 J 106 j
… … … … … … … …
18
capitalize.cpp
...
char s[] = "Hello World";
int ascii_code(0);
int i(0);
i = 0;
while(s[i] != '\0')
{
ascii_code = int(s[i]);
if (97 <= ascii_code && ascii_code <= 122)
{ ascii_code = ascii_code-32; }
cout << char(ascii_code);
i++;
}
cout << endl;
...
19
…
i = 0;
while(s[i] != '\0')
{
ascii_code = int(s[i]);
if (97 <= ascii_code && ascii_code <= 122)
{ ascii_code = ascii_code-32; }
cout << char(ascii_code);
i++;
}
…
> capitalize.exe
Hello World
HELLO WORLD
20
passLiteral.cpp
...
int main()
{
int x1, y1;
int x2, y2;
return 0;
}
...
21
passLiteral.cpp
...
void read_point(const char prompt[], int & x, int & y);
void write_point(const char label[], int x, int y);
int main()
{
int x1, y1;
int x2, y2;
return 0;
}
...
22
Functions read_point() and write_point()
23
…
read_point("Enter first point: ", x1, y1);
read_point("Enter second point: ", x2, y2);
…
> passLiteral.exe
Enter first point: 10 20
Enter second point: 3 5
First point: (10,20)
Second point: (3,5)
24
…
write_point("First point: ", x1, y1);
write_point("Second point: ", x2, y2);
…
> passLiteral.exe
Enter first point: 10 20
Enter second point: 3 5
First point: (10,20)
Second point: (3,5)
25
(Major) Problems with C-style Strings
const int MAX_LENGTH(20);
char s[MAX_LENGTH] = { 'H', 'e', 'l', 'l', 'o', '\0'};
cout << "String = " << s << endl;
26
C++ Strings
C++ class string
• C++ class string requires:
#include <string>
using namespace std;
Or
string lastname = “Marx”;
28
String Operators: Assignment
• Assignment (=): As with before, assign a
string to a variable of type string.
anothername = lastName;
29
String Operators: Concatentation
string firstName(“Groucho”);
string lastName(“Marx”);
string fullname = firstName + lastname;
30
concatString.cpp
#include <iostream>
#include <string> // <--------- Note
using namespace std;
int main()
{
string name1("Groucho“), name2(“Harpo”);
string lastName("Marx“);
31
concatString.cpp
#include <iostream>
#include <string> // <--------- Note
...
{
string name1("Groucho“), name2(“Harpo”);
string lastName("Marx“);
> concatString.exe
GrouchoMarx
HarpoMarx
32
concatString2.cpp
#include <iostream>
#include <string> // <--------- Note
using namespace std;
int main()
{
string name1("Groucho“), name2(“Harpo”);
string lastName("Marx“);
33
concatString2.cpp
#include <iostream>
#include <string> // <--------- Note
...
{
string name1("Groucho“), name2(“Harpo”);
string lastName("Marx“);
> concatString.exe
Groucho Marx
Harpo Marx
34
C++ String I/O
Input/Output with Strings
• I/O with Strings are as before:
string lastName;
36
getName.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string firstName, lastName, fullName;
// concatenate
fullName = firstName + " " + lastName;
cout << "Your name is: " << fullName << endl;
37
getName.cpp
string firstName, lastName, fullName;
// concatenate
fullName = firstName + " " + lastName;
cout << "Your name is: " << fullName << endl;
> getName.exe
Enter your first name: Groucho
Enter your last name: Marx
Your name is: Groucho Marx
38
getName2.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string fullName;
return 0;
}
39
getName2.cpp
...
string fullName;
> getName2.exe
Enter your full name: Groucho Marx
Your name is: Groucho
40
Input/Output with Strings
• A common problem with reading strings from
user input is that it could contain white spaces.
• cin uses white space (e.g. space, tab, newline)
as a delimiter between inputs;
> getName2.exe
Enter your full name: Groucho Marx
Your name is: Groucho
41
String I/O: getline()
• Fortunately, the string class let’s us get
around this with the getline() function.
42
String I/O: getline()
• We can fix our code by rewriting it as
follows:
string fullname;
43
getName3.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string fullName;
return 0;
}
44
getName3.cpp
...
cout << "Enter your full name: ";
getline(cin, fullName); // <--------- Note
cout << "Your name is: " << fullName << endl;
...
> getName3.exe
Enter your full name: Groucho Marx
Your name is: Groucho Marx
> getName3.exe
Enter your full name: Groucho G. Marx III
Your name is: Groucho G. Marx III
45
getName3.cpp
...
cout << "Enter your full name: ";
getline(cin, fullName); // <--------- Note
cout << "Your name is: " << fullName << endl;
...
> getName3.exe
Enter your full name: Groucho Marx
Your name is: Groucho Marx
> getName3.exe
Enter your full name:
Your name is:
46
C++ String Processing
str[k]
• s[k] represents the k’th character in string s:
48
String Processing (2)
• s[k] represents the (k+1)’st character in string s:
s[1] = ‘o’;
s[2] = ‘w’;
s[3] = ‘d’;
s[4] = ‘y’;
49
Relational String Operators
== !=
< <=
> >=
50
...
relationOps.cpp
string s1, s2;
cout << "Enter first string: ";
getline(cin, s1);
if (s1 == s2)
{
cout << s1 << " equals " << s2 << endl;
}
else if (s1 < s2)
{
cout << s1 << " < " << s2 << endl;
}
else
{
cout << s1 << " > " << s2 << endl;
}
51
relationOps.cpp
if (s1 == s2)
{
cout << s1 << " equals " << s2 << endl;
}
else if (s1 < s2)
{
cout << s1 << " < " << s2 << endl;
}
else
{
cout << s1 << " > " << s2 << endl;
}
> relationOps.exe
Enter first string: hello
Enter last string: howdy
hello < howdy
52
relationOps.cpp
if (s1 == s2)
{
cout << s1 << " equals " << s2 << endl;
}
else if (s1 < s2)
{
cout << s1 << " < " << s2 << endl;
}
else
{
cout << s1 << " > " << s2 << endl;
}
> relationOps.exe
Enter first string: hello
Enter last string: Howdy
hello > Howdy
53
relationOps.cpp
if (s1 == s2)
{
cout << s1 << " equals " << s2 << endl;
}
else if (s1 < s2)
{
cout << s1 << " < " << s2 << endl;
}
else
{
cout << s1 << " > " << s2 << endl;
}
> relationOps.exe
Enter first string: Hello
Enter last string: Hello World
54
relationOps.cpp
• Blanks matter:
> relationOps.exe
Enter first string: HelloWorld
Enter last string: Hello World
HelloWorld > Hello World
55
sortNames.cpp
...
int main()
{
const int MAX_SIZE(50);
string name[MAX_SIZE];
int num_names(0), i(0);
string s;
// Read names
i = 0;
cout << "Enter name: ";
cin >> s;
while (s != ".“ && i < MAX_SIZE)
{
name[i] = s;
i++;
cout << "Enter name: ";
cin >> s;
}
num_names = i;
...
56
sortNames.cpp (2)
...
// Sort names
for (int i = num_names-1; i > 0; i--)
{
// Compare name[j] with name[i], j < i
for (int j = 0; j < i; j++)
{
if (name[j] > name[i])
{
swap(name[j], name[i]);
}
}
// name[i] is now in its correct location
}
...
57
sortNames.cpp (3)
...
// Output names
cout << endl;
cout << "Names in alphabetic order:" << endl;
for (int i = 0; i < num_names; i++)
{
cout << name[i] << endl;
}
return 0;
}
58
String Processing
• In addition to giving us a new data type to
hold strings, the string library offers many
useful string processing methods.
59
length()
• This method returns the integer length of the
string. (Note: Parentheses “()” after length().)
• Example:
string s1(“Super!”);
60
easyFrench.cpp
int main()
{
string s;
cout << "Enter phrase in English: ";
getline(cin, s);
• Example:
//outputs “Ship”
cout << transport.substr(7, 4) << endl;
62
replace(index, n, str)
• Removes n characters in the string starting from
the specified index, and inserts the specified
string, str, in its place.
• Example:
transport.replace(0, 5, “Sail”);
63
advancedFrench.cpp
// example of using C++ class string
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout << "Enter phrase in English: ";
getline(cin, s);
64
advancedFrench.cpp
...
for (int i = 0; i < s.length(); i++)
{
if (s[i] == 's')
{
s[i] = 'z';
}
else if (s[i] == 'w')
{
s[i] = 'v';
}
else if (s.substr(i, 5) == " the ")
{
s.replace(i, 5, " la ");
}
}
65
insert(index, str)
• Inserts the specified string at the specified index.
• Example:
string animal(“Hippo”);
66
outputFileName.cpp
// construct an output file name from the input file name
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input_filename, output_filename;
int length(0);
67
outputFileName.cpp
...
length = input_filename.length();
output_filename = input_filename;
if (input_filename.substr(0,2) == "in")
{
output_filename.replace(0,2,"out");
}
else
{
output_filename.insert(0, "out.");
}
cout << "Output file name: " << output_filename << endl;
return 0;
}
68
CanadianError.cpp
...
int main()
{
string s;
cout << "Enter phrase in English: ";
getline(cin, s);
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '.' || s[i] == '?')
{
s.replace(i, 1, ", eh?");
}
}
cout << "Canadian version: ";
cout << s << endl;
return 0;
}
69
Canadian.cpp
...
int main()
{
string s;
cout << "Enter phrase in English: ";
getline(cin, s);
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '.' || s[i] == '?')
{
s.replace(i, 1, ", eh?");
i = i + 4; // Why 4?
}
}
cout << "Canadian version: ";
cout << s << endl;
return 0;
}
70
Literal vs. C++ strings
• Literal strings end in a null character: ‘\0’.
(Character ‘\0’ has ASCII code 0.)
char s[] = “Hello World”;
– s[11] equals ‘\0’;
71
Passing Strings to Functions
outputFileName.cpp
...
length = input_filename.length();
output_filename = input_filename;
if (input_filename.substr(0,2) == "in")
{
output_filename.replace(0,2,"out");
}
else
{
output_filename.insert(0, "out.");
}
cout << "Output file name: " << output_filename << endl;
...
73
Function construct_output_filename()
void construct_output_filename
(string & in_name, string & out_name)
{
out_name = in_name;
if (in_name.substr(0,2) == "in")
{
out_name.replace(0,2,"out");
}
else
{
out_name.insert(0, "out.");
}
}
74
outputFileName2.cpp
...
void construct_output_filename
(string & in_name, string & out_name);
int main()
{
string input_filename, output_filename;
construct_output_filename(input_filename, output_filename);
cout << "Output file name: " << output_filename << endl;
return 0;
}
75