Chapter 4 - Strings
Chapter 4 - Strings
Syntax Error
4.3.7 String operators: +=
To be or not to be
4.3.8 Inputting strings
• cin stream treats spaces as delimiters, demarcating limits
between data
To be or not to be
To
4.3.8 Inputting strings
• If you want to input a whole line of text and treat the
white characters just like any other character, you have to
use the getline function.
To be or not to be
To be or not to be
4.3.10 Comparing strings
• you can compare two strings .
• All the operators designed to compare data are at your
disposal: > < >= <= !=.
4.3.10 Comparing strings
• Using the compare function
• str1.compare(str2) == 0 when str1 == str2
• str1.compare(str2) == 1 when str1 > str2
• str1.compare(str2) == -1 when str1 < str2
4.4.1 string length and empty functions
• To obtain the length of a string object x, call the method
length() or size():
bool y = str.empty();
15
Example 1 0
Not Empty string
Empty string
• What is the output?
4.4.2 Substrings
•A substring of a string x is a subsequence of consecutive characters
in x
•For example, “rod” is a substring of “product”
x.substr(pos,len);
string S = "ABC";
cout << S.compare(1,1,"B");
Will print 0
4.4.3 compare
• S.compare(substr_start, substr_length,
other_string, other_substr_start,
other_substr_length)
string S = "ABC";
cout << S.compare(1,1,"ABC",1,1);
Will print 0
4.4.4 Finding strings inside strings
• Suppose x is a string object, and suppose you want to
search for a string y in x.
• To do so, write:
• Example:
• enter a string and print each char in a separate line
4.5.1 Appending a (sub)string
• Append function it’s designed to append one string to
another
• Examples:
• string str1 = "content“, str2 =
"appendix"; str1.append(str2);
• // str1 contains "contentappendix" now
x.insert(pos,y);
• Example