C++ Strings
C++ Strings
234 LECTURE 17
18
C++ Strings
1
C ++ Strings
– Formatted Input: Stream extraction operator
• cin >> stringObject;
• the extraction operator >> formats the data that it receives
through its input stream; it skips over whitespace
string s = “ABCDEFG”;
getline(cin, s); //reads entire line of characters into s
char c = s[2]; //assigns ‘C’ to c
S[4] = ‘*’; //changes s to “ABCD*FG” 3
C ++ Strings
4
C ++ Strings 18
String Objects
string s = “ABCDEFG”;
const char* cs = s.c_str();
6
C ++ Strings 18
String Objects
The C++ string class also defines a length() function for extracting
how many characters are stored in a string.
String Objects
while(s4==s3) //…
8
compare.cpp
C ++ Strings 18
String Objects
You can also concatenate C++ strings using the + and += operators:
string s = “ABCD*FG”;
string s2 = “Robot”;
string s5 = “Soccer”;
string s6 = s + “HIJK”; //changes s6 to “ABCD*FGHIJK
9
C ++ Strings 18
String Objects
s6 = “ABCD*FGHIJK”;
s4 = s6.substr(5, 3); //changes s4 to “FGH”
10
C ++ Strings 18
String Objects
s6 = “ABCD*FGHIJK”;
s6.erase(4, 2); //changes s6 to “ABCDGHIJK”;
11
C ++ Strings 18
String Objects
find() function
returns the index of the first occurrence of a given substring:
• Assignment
– s2 = s1;
• Makes a separate copy
– s2.assign(s1);
• Same as s2 = s1;
– myString.assign(s, start, N);
• Copies N characters from s, beginning at index start
– Individual character assignment
• s2[0] = s3[2];
13
Range-checking
• Range-checking
– s3.at( index );
• Returns character at index
• Can throw an out_of_range exception
– [] has no range checking
#include <exception>
...
string s = "leon";
try{
char letter = s.at( 50 );
cout <<"letter is = " << letter << endl;
}
catch(exception& e){
cout << "out_of_range exception: " << e.what() << endl;
}
14
string_characteristics.cpp
Concatenation
• Concatenation
– s3.append( "pet" );
– s3 += "pet";
• Both add "pet" to end of s3
– s3.append( s1, start, N );
• Appends N characters from s1,
s1 beginning at index start
15
Comparing strings
• Overloaded operators
– ==, !=, <, >, <= and >=
– returns bool
• s1.compare(s2)
– returns positive if s1 is lexicographically greater
• compares letter by letter
• 'B' lexicographically greater than 'A‘
• ‘a’ lexicographically greater than ‘A‘
• ‘a’ lexicographically greater than ‘Z‘
– returns negative if less; zero if equal
• Sample order: ‘A’,”Apple”, “Banana”, “Zest”, ‘a’, “apricot”, “leon”
– s1.substr( start, N );
– gets N characters, beginning with index start
– returns substring
17
Swapping strings
• s1.swap(s2);
– Switch contents of two strings
18
string Characteristics
• Member functions
– s1.size() and s1.length()
• Number of characters in a string
– s1.capacity()
• Number of elements that can be stored without reallocation
– s1.max_size()
• Maximum possible string size
– s1.empty()
• Returns true if empty
– s1.resize(newlength)
• Resizes string to newlength
19
string_characteristics.cpp
Finding Strings and Characters in a string
• Find functions
– If found, index returned
– If not found, string::npos returned
• Public static constant in class string
– s1.find( s2 )
– s1.rfind( s2 )
• Searches right-to-left
– s1.find_first_of( s2 )
• Returns first occurrence of any character in s2
• Find functions
– s1.find_last_of( s2 )
• Finds last occurrence of any character in s2
– s1.find_first_not_of( s2 )
• Finds first character NOT in s2
– s1.find_last_not_of( s2 )
• Finds last character NOT in s2
21
others.cpp
Replacing Characters in a string
• s1.erase( start )
– Erase from index start to end of string, including
start
• Replace
– s1.replace( begin, N, s2)
• begin: index in s1 to start replacing
• N: number of characters to replace
• s2: replacement string
– s1.replace( begin, N, s2, index, num )
• index: element in s2 where replacement comes from
• num: number of elements to use when replacing
– Replace can overwrite characters
22
others.cpp
Example
s1.replace( begin, N, s2, index, num )
23
Inserting Characters into a string
• s1.insert( index, s2 )
– Inserts s2 before position index
• s1.insert( index, s2, index2, N );
– Inserts substring of s2 before position index
– Substring is N characters, starting at index2
24
others.cpp
Conversion to C-Style char*
• Conversion functions
– Strings are not necessarily null-terminated
– s1.copy( ptr, N, index )
• Copies N characters into the array ptr
• Starts at location index
• Need to null terminate
char str[8];
string s2 = "cathode";
Output:
s2.copy(str, 5, 2); //copy 5 characters into str
//starting at index 2
str = thode
//strcat(str,"\0"); //does not work s2 = cathode
str[5] = '\0'; //this is required
– s1.c_str()
• Returns const char *
• Null terminated
• e.g. Useful for filenames:
ifstream in( s1.c_str() );
– s1.data()
• Returns const char *
• NOT null-terminated
26
Warning!
• No conversion from int or char
28
Output String Stream
ostringstream oss;
int n = 44;
float x = 3.14;
All extractions from iss will come from the contents of buffer, as
30
if
it were an external file.
file
#include <iostream>
#include <fstream> Using string example
#include <iomanip>
#include <string> • Input file:
#include <sstream> 1.0 2.0
using namespace std; 1.1 2.4
int main(){ 1.8 2.8
#1.34 2.99
string s1("mydata.txt"); 1.4 8.99
ifstream in( s1.c_str() );
• Example Output:
char buffer[1024]; Line is:1.0 2.0
while( in.getline( buffer, 1024 ) ){ 1,2
Next Templates
33
Method Use
append(char *pt);
append(char *pt, size_t count);
append(string &str, size_t
offset,size_t count);
Appends characters to a string from C-style strings, char's or other string objects.
append(string &str);
append(size_t count, char ch);
append(InputIterator Start,
InputIterator End);
Returns a reference to the character at the specified position. Differs from the
at(size_t offset);
subscript operator, [], in that bounds are checked.
begin(); Returns an iterator to the start of the string.
*c_str(); Returns a pointer to C-style string version of the contents of the string.
clear(); Erases the entire string.
copy(char *cstring, size_t count,
Copies "count" characters into a C-style string starting at offset.
size_t offset);
empty(); Test whether a string is empty.
end(); Returns an iterator to one past the end of the string.
erase(iterator first, iterator last);
erase(iterator it); Erases characters from the specified positions.
erase(size_t pos, size_t count);
34
Method Use
Same sets of arguments as find. Finds the index of the first character that is not
find_first_not_of();
in the search string.
Same sets of arguments as find. Finds the index of the first character that is in
find_first_of();
the search string.
Same sets of arguments as find. Finds the index of the last character that is not in
find_last_not_of();
the search string.
Same sets of arguments as find. Finds the index of the last character that is in the
find_last_of();
search string.