Академический Документы
Профессиональный Документы
Культура Документы
String Manipulation
Introduction
#include <string>
W6&7-Operator Overloading
3
Character constants
'a', 'b', 'c', …'z', '0', '1', … '9', '+', '-', '=',
'!', '~', etc, '\n', '\t', '\0', etc.
A-Z, a-z, 0-9 are in order, so that arithmetic can be done
W6&7-Operator Overloading
Strings in C
W6&7-Operator Overloading
W6&7-Operator Overloading
Character Functions in C
<ctype.h>
W6&7-Operator Overloading
W6&7-Operator Overloading
W6&7-Operator Overloading
W6&7-Operator Overloading
String Constructors
string();
For creating an empty string.
string(const char *str);
For creating a string object from a null-
terminated string.
string(const string &str);
For creating a string object from other string
object.
W6&7-Operator Overloading
s3 += s1; // s3 = s3 + s1;
s3 += “abc”; // s3 = s3 + “abc”;
W6&7-Operator Overloading
string s1(“12345”);
string s2(“abcde”);
s1.insert(4, s2); // s1 = 1234abcde5
s1.erase(4, 5); // s1 = 12345
W6&7-Operator Overloading
string s1(“ABC”);
string s2(“XYZ”);
int x = s1.compare(s2);
x == 0 if s1 == s2
x > 0 if s1 > s2
x < 0 if s1 < s2
W6&7-Operator Overloading
s1.swap(s2)
Exchanges the content of string s1 and s2
W6&7-Operator Overloading
Function Task
size() Number of elements currently stored
length() Number of elements currently stored
max_size() Maximum size of a string object that a system can
support
empty() Return true or 1 if the string is empty otherwise
returns false or 0
resize() Used to resize a string object (effects only size and
length)
W6&7-Operator Overloading
String Characteristics
W6&7-Operator Overloading
Function Task
at() For accessing individual characters
substr() For retrieving a substring
find() For finding a specific substring
find_first_of() For finding the location of first occurrence of the specific
character(s)
find_last_of() For finding the location of last occurrence of the specific
character(s)
W6&7-Operator Overloading
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
W6&7-Operator Overloading
19
W6&7-Operator Overloading
20
int main()
{
const int DAYS = 7; //number of strings in array
const int MAX = 10; //maximum size of each string
//array of strings
char star[DAYS][MAX]={“Sunday”, “Monday”,
“Tuesday”,“Wednesday”, “Thursday”,“Friday”, “Saturday” };
W6&7-Operator Overloading
21
W6&7-Operator Overloading
22
W6&7-Operator Overloading
23
W6&7-Operator Overloading
24