C-strings and
C++ string Class
Topics
• C-StringsC-Strings
• Library Functions for Working with C-StringsLibrary Functions for Working with C-Strings
• Conversions Between Numbers and StringsConversions Between Numbers and Strings
• Character TestingCharacter Testing
• Character Case ConversionCharacter Case Conversion
• Writing Your Own C-String Handling FunctionsWriting Your Own C-String Handling Functions
• C++ C++ stringstring Class Class
Strings• C-stringC-string: array of characters terminated by : array of characters terminated by NULLNULL character character
• The C-string The C-string
"Hi there!""Hi there!"
would be stored in memory as shown: would be stored in memory as shown:
12-3
H i t h e r e ! \0
Array of char
• Array of char can be defined and initialized Array of char can be defined and initialized to a C-stringto a C-string
char str1[20] = "hi there!";char str1[20] = "hi there!";• Array of char can be defined and later have Array of char can be defined and later have
a string copied into ita string copied into it
char str2[20];char str2[20];
strcpy(str2, "hi there!");strcpy(str2, "hi there!");
12-4
Pointer to char• Pointer to Pointer to charchar can refer to C-strings defined can refer to C-strings defined
as arrays of charas arrays of char
char str[20] = "hi";char str[20] = "hi";
char *pStr = str;char *pStr = str;
cout << pStr; // prints hicout << pStr; // prints hi• Can dynamically allocate memory to be used Can dynamically allocate memory to be used
for C-string using for C-string using newnew
12-5
Library Functions for C-Strings(Requires #include <cstring>)(Requires #include <cstring>)• int strlen(char *str)int strlen(char *str) // // Returns length of a C-string:Returns length of a C-string:
cout << strlen("hello");cout << strlen("hello"); // // Prints: Prints: 55
12-6
const int LENGTH = 30;char line[LENGTH];
cout << "Enter a string (no more than " << LENGTH - 1 << " characters.)\n";cin.getline(line, LENGTH);
cout << "The C-string read was " << "\"" << line << "\"" << " whose length was " << strlen(line) << endl;
strcpy
• char name[20] = “Mary” char name[20] = “Mary” // This is OK// This is OK
char name2[20];char name2[20];name2 = “Nancy”; name2 = “Nancy”; // Now allowed// Now allowed
char name3[20];char name3[20];strcpy(name3, “Nancystrcpy(name3, “Nancy”); //”); // CopyCopy
cout << name3; cout << name3; // Prints Nancy// Prints Nancy
12-8
strcpy
• strcpy(charstrcpy(char *dest, char *source) *dest, char *source)
// Copies a string from a source address // Copies a string from a source address // to a destination address // to a destination address
char name[15];char name[15];
strcpy(name, "Deborah");strcpy(name, "Deborah");
cout << name; // cout << name; // prints Deborahprints Deborah
12-9
strcat• strcat(char *dest, char *source)strcat(char *dest, char *source) //// Takes two C-strings as input. Takes two C-strings as input. // Adds the contents of the second string to the // Adds the contents of the second string to the // end of the first string: // end of the first string:
char str1[15] = "Good ";char str1[15] = "Good "; char str2[30] = "Morning!";char str2[30] = "Morning!"; strcat(str2, str1);strcat(str2, str1); cout << str1; // cout << str1; // prints: Good Morning!prints: Good Morning!
• No automatic bounds checking: programmer must No automatic bounds checking: programmer must ensure that str1 has enough room for resultensure that str1 has enough room for result
12-10
strcmp
• intint strcmp(charstrcmp(char *str1,*str1, char*str2)char*str2) //// Compares strings stored at two addressesCompares strings stored at two addresses
• Returns a value:Returns a value:
less than 0 if less than 0 if str1str1 precedes precedes str2str2
equal to 0 if equal to 0 if str1str1 equals equals str2str2
greater than 0 if greater than 0 if str1str1 succeeds succeeds str2str2
12-11
strcmp• Often used to test for equalityOften used to test for equality
if(strcmp(str1, str2) == 0)if(strcmp(str1, str2) == 0)
cout << "equal"; cout << "equal";
else else
cout << "not equal";cout << "not equal";
• Also used to determine ordering of C-strings in sorting applicationsAlso used to determine ordering of C-strings in sorting applications• Note that C-strings cannot be compared using == or >Note that C-strings cannot be compared using == or >
if (str1 > str2) -- this is not allowed if (str1 > str2) -- this is not allowed(compares addresses of C-strings, not contents)(compares addresses of C-strings, not contents)
• If If •
12-12
Swapping
const int NAME_LENGTH = 20;const int NAME_LENGTH = 20;char name1[NAME_LENGTH];char name1[NAME_LENGTH];char name2[NAME_LENGTH];char name2[NAME_LENGTH];char temp[NAME_LENGTH];char temp[NAME_LENGTH];
strcpy(name1, "William"); strcpy(name1, "William"); strcpy(name2, "Catherine"); strcpy(name2, "Catherine"); cout << "Originally...\n";cout << "Originally...\n";cout << "Name1: " << name1 << endl;cout << "Name1: " << name1 << endl;cout << "Name2: " << name2 << endl;cout << "Name2: " << name2 << endl;
12-13
Swapping (cont.)
if (strcmp(name1, name2) > 0)if (strcmp(name1, name2) > 0){{ strcpy(temp, name1); strcpy(temp, name1); strcpy(name1, name2); strcpy(name1, name2); strcpy(name2, temp); strcpy(name2, temp);
}}
cout << "\nAfter switch...\n";cout << "\nAfter switch...\n";cout << "Name1: " << name1 << endl;cout << "Name1: " << name1 << endl;cout << "Name2: " << name2 << endl;cout << "Name2: " << name2 << endl;
12-14
Character Testing
Requires #include <Requires #include <cctype>cctype>
FUNCTION MEANING
isalpha() true if arg. is a letter, false otherwise
isalnum() true if arg. is a letter or digit, false otherwise
isdigit() true if arg. is a digit 0-9, false otherwise
islower() true if arg. is lowercase letter, false otherwise
12-15
Character Testing
Require #include<Require #include<cctype>cctype>
FUNCTION MEANING
isprint() true if arg. is a printable character, false otherwise
ispunct() true if arg. is a punctuation character, false otherwise
isupper() true if arg. is an uppercase letter, false otherwise
isspace() true if arg. is a white space character, false otherwise
12-16
C++ String Class
The C++ string Class
• The string class offers several advantages over The string class offers several advantages over C-style strings:C-style strings:
large body of member functionslarge body of member functionsoverloaded operators to simplify expressionsoverloaded operators to simplify expressions
• Requires #include <Requires #include <stringstring>>
12-18
string class constructors
• string()string()• string(string str)string(string str) initializes string initializes string
object with strobject with str• string(char *cstr)string(char *cstr) initializes string initializes string
ojbect with C-stringojbect with C-string
• Various other constructorsVarious other constructorswww.cplusplus.com
12-19
String Class Member Functions• int find(string str)int find(string str)
// returns the position of str in the string object // returns the position of str in the string object
• int find (char ch)int find (char ch) // returns the position of ch in the string object // returns the position of ch in the string object
• int find (string str, int x)int find (string str, int x) // returns the position of str beyond x // returns the position of str beyond x
• int find (ch ch, intx)int find (ch ch, intx) // returns the position of ch beyond // returns the position of ch beyond
String Class Member Functions (cont.)• void insert (int x, string str)void insert (int x, string str)
// inserts str at position x // inserts str at position x
• void insert (int x, char ch)void insert (int x, char ch) // inserts char at position x // inserts char at position x
• string replace(int pos, int n, string str)string replace(int pos, int n, string str) // replaces n characters starting at pos with // replaces n characters starting at pos with // substring str // substring str
• Other member functions Other member functions www.cplusplus.com
Overloaded string Operators
OPERATOR MEANING
>> reads whitespace-delimited strings into string object
<< outputs string object to a stream
= assigns string on right to string object on left
+= appends string on right to end of contents of string on left
12-22
Overloaded string Operators (continued)
OPERATOR MEANING
+ Returns concatenation of the two strings
[] references character in string using array notation
>, >=, <, <=, ==, !=
relational operators for string comparison. Return true or false
12-23
Overloaded string Operators
string word1, phrase;string word1, phrase;string word2 = " Dog";string word2 = " Dog";cin >> word1; // user enters "Hot"cin >> word1; // user enters "Hot" // word1 has "Hot"// word1 has "Hot"phrase = word1 + word2; // phrase hasphrase = word1 + word2; // phrase has // "Hot Dog"// "Hot Dog"phrase += " on a bun";phrase += " on a bun";for (int i = 0; i < 16; i++)for (int i = 0; i < 16; i++) cout << phrase[i]; // displayscout << phrase[i]; // displays // "Hot Dog on a bun"// "Hot Dog on a bun"
12-24
Swapping Two Strings string name1 = "William"; string name2 = "Catherine"; string temp;
cout << "Originally...\n"; cout << "Name 1: " << name1 << endl; cout << "Name 2: " << name2 << endl;
if (name1 > name2){ temp = name1; name1 = name2; name2 = temp; } cout << "\nAfter swap...\n"; cout << "Name 1: " << name1 << endl; cout << "Name 2: " << name2 << endl;
Conversion to C-strings
• data()data() and and c_str()c_str() both return the C- both return the C-string equivalent of a string equivalent of a stringstring object object
• Useful when using a string object with a Useful when using a string object with a function that is expecting a C-stringfunction that is expecting a C-string
char greeting[20] = "Have a ";char greeting[20] = "Have a ";
string str("nice day");string str("nice day");
strcat(greeting, str.data());strcat(greeting, str.data());
12-26
Modification of string objects
• str.insert(int pos, string s)str.insert(int pos, string s)
inserts inserts ss at position at position pospos in in strstr• Convert constructor for Convert constructor for stringstring allows a allows a
C-string to be passed in place of C-string to be passed in place of ss
string str("Have a day");string str("Have a day");
str.insert(7, "nice ");str.insert(7, "nice ");• insertinsert is overloaded for flexibility is overloaded for flexibility
12-27
Modification of string objects
• str.append(string s)str.append(string s)
appends contents of appends contents of ss to end of to end of strstr• Convert constructor for Convert constructor for stringstring allows a allows a
C-string to be passed in place of C-string to be passed in place of ss
string str("Have a ");string str("Have a ");
str.append("nice day");str.append("nice day");• appendappend is overloaded for flexibility is overloaded for flexibility
12-28
Your Turn(Formatting Number)
• Problem: Design a function which formats a Problem: Design a function which formats a string like “1234567.89” to string like “1234567.89” to “$1,234,567.89”.“$1,234,567.89”.
• Plan:Plan:– Find the position dp of the decimal pointFind the position dp of the decimal point– Starting at dp, count backwards and insert a Starting at dp, count backwards and insert a
comma every 3 places.comma every 3 places.– At position 0, insert ‘$’.At position 0, insert ‘$’.
Refinement
• dp dp position of decimal point in string position of decimal point in stringpos pos dp dp
• Loop (while dp is greater than 3)Loop (while dp is greater than 3) go back 3 places in the string go back 3 places in the string insert ‘,’ there insert ‘,’ thereEnd LoopEnd Loop
• Insert “$” at front of stringInsert “$” at front of string
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 . 9 5
dp
Your Turn
• Write a program which inputs a long text Write a program which inputs a long text and counts the frequency of occurrence of and counts the frequency of occurrence of each letter in the text.each letter in the text.
0 1 2 3 4 5 … 23 24 25
8 1 2 2 20 3 … 1 7 0
letters
frequency
In Main() // Declarations const int MAX = 26; int frequency[MAX]; string text; cout << "Please enter a “ + “substantially long text.\n"; getline(cin, text); string input(text); // convert to // c-string letterFrequency(frequency, MAX, input);
Letter Frequency
• The quick brown fox jumps over the lazy dog.
• Pack my box with five dozen liquor jugs.
• Now is the time for all good people to come to the aid of their country.
letterFrequency()void letterFrequency(int frequency[], int count, string input) { // Initialize requency for (int i = 0; i < count; i++){ frequency[i] = 0; } // Count frequency int length = input.length(); for (int i = 0; i < length; i++) { switch(input[i]) { case 'a': case 'A': frequency[0]++; break; case 'b': case 'B': frequency[1]++; break;
letterFrequency() (cont.) case 'c': case 'C': frequency[2]++; break; case 'd': case 'D': frequency[3]++; break; case 'e': case 'E': frequency[4]++; break; . . . . . .; case 'x': case 'X': frequency[23]++; break; case 'y': case 'Y': frequency[24]++; break; case 'z': case 'Z': frequency[25]++; break; default:; } // switch }}
String I/O
• string str1;string str1;cin >> str1; // delimitted bycin >> str1; // delimitted by // white-space // white-spacecout << str1;cout << str1;
• string str2;string str2;getline(cin, str2);getline(cin, str2); // delimitted by // delimitted by // by eol // by eol
Your Turn
• Problem:Problem:– Input a long sentence and count the number of Input a long sentence and count the number of
words. words.
• Assumption:Assumption:– All words are delimitted by a single space.All words are delimitted by a single space.
In Main()
• // Input text// Input text
• // wordCount = countWords(text)// wordCount = countWords(text)
• // Output results// Output results
countWords()
• int countWords(string text)int countWords(string text) Loop (while length > 0 && !done) Loop (while length > 0 && !done) ps ps position of ‘ ‘ in text position of ‘ ‘ in text If (ps = 0) If (ps = 0) done done true true End If End If Add one to count Add one to count Replace first part of text with “” Replace first part of text with “”
• End LoopEnd Loop