0% found this document useful (0 votes)
38 views25 pages

Lec-10

The document discusses C++ string objects and their member functions. It describes how to initialize strings, input and output strings, compare strings, concatenate strings, find and replace substrings within strings, and more. Key functions covered include append(), assign(), find(), replace(), substr(), and relational operators for comparing strings.

Uploaded by

Vinay Prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views25 pages

Lec-10

The document discusses C++ string objects and their member functions. It describes how to initialize strings, input and output strings, compare strings, concatenate strings, find and replace substrings within strings, and more. Key functions covered include append(), assign(), find(), replace(), substr(), and relational operators for comparing strings.

Uploaded by

Vinay Prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

CSE101-Lec#11

String Object

Created By:
Amanpreet Kaur &
Sanjeev Kumar
SME (CSE) LPU

Formatted Input: Stream extraction operator


cin >> stringObject;
the extraction operator >> formats the data
that it receives through its input stream; it skips
over whitespace
Unformatted Input: getline function for a
string
getline( cin, s)
does not skip over whitespace
delimited by newline
reads an entire line of characters into s
3

string s = ABCDEFG;
getline(cin, s); //reads entire line of characters
into s

Not necessarily null terminated


string is not a pointer, but a class
Many member functions take start
position and length
If length argument too large, max chosen

Creating String Objects


#include <string>
//string initialization

string type in the <string>


header file.

string s; //s contains 0 characters


string s1( "Hello" ); //s1 contains 5 characters
string s2 = Hello; //s2 contains 5 characters
//implicitly calls the constructor
string s3( 8, 'x' ); //s3 contains 8 'x' characters
string s4 = s3;
//s4 contains 8 'x' characters
string s5(s2, 3, 2); //s5 copies a substring of s2; it contains lo

string_characteristics.cpp

String Objects
The C++ string class also defines a length() function for extracting
how many characters are stored in a string.

cout << s.length() << endl;


Prints 4 for the string s == Leon

You can also use the subscript operator [ ] to access individual


characters:
e.g.
s[0] = N ;
//where index: 0 to length-1

String Objects

C++ strings can be compared using relational operators just like


fundamental types:
If(s2 < s5)
cout << s2 lexicographically precedes s5 \n;
while(s4==s3) //

'B' is lexicographically greater than 'A'


7

Sample order: A,Apple, Banana, Zest, a, apricot,


leon

compare.cpp

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
s2 += s5; //changes s2 to RobotSoccer
8

String Objects

Substring function:

substr()

s6 = ABCD*FGHIJK;
s4 = s6.substr(5, 3); //changes s4 to FGH

s4 gets a substring of s6, starting at index 5 and taking 3


characters

String Objects

erase() and replace() functions:


s6 = ABCD*FGHIJK;
s6.erase(4, 2); //changes s6 to ABCDGHIJK;
s6.replace(5, 2, xyz); //changes s6 to ABCDGxyzJK;
replace 2 characters from s6, starting at
index 5, with xyz
10

String Objects

find() function
returns the index of the first occurrence of a given substring:
string s7 = Mississippi River basin; //23 characters
cout << s7.find(si) << endl; //prints 3
cout << s7.find(so) << endl; //prints 23, the length of the string

If the find() function fails, it returns the


length of the string it was searching.
11

i.e.

find() returns 4,294,967,295

Assignment
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];

12

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;
}

13

catch(exception& e){
cout << "out_of_range exception: " << e.what() << endl;
}
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, beginning at index
start

14

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.compare(start, length, s2, start, length)


Compare portions of s1 and s2

15

s1.compare(start, length, s2)


Compare portion of s1 with all of s2

Compare.cpp

Substrings
Function substr gets a substring
s1.substr( start, N );
gets N characters, beginning with index
start
returns substring

16

Swapping strings
s1.swap(s2);
Switch contents of two strings

17

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)
18

Resizes string to newlength


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
Example:
19

s1.find_first_of( "abcd" )

Returns index of first 'a', 'b', 'c' or 'd'


others.cpp

Finding Strings and Characters in a string

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
20

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 )

21

index: element in s2 where replacement comes


from
num: number of elements to use when replacing

Replace can overwrite characters

others.cpp

Example
s1.replace( begin, N, s2, index, num )
begin: index in s1 to start replacing
N: number of characters to replace
s2: replacement string
index: element in s2 where replacement comes
from
num: number of elements to use when replacing
string str = "this is an example string.";
string str3="sample phrase";
str.replace(19,6, str3, 7, 6);
22

// "this is an example phrase."

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

23

others.cpp

Summary
C++ strings are safer and easier to use than C string.

24

25

Method

Use

append(char *pt);
append(char *pt, size_t count);
append(string &str, size_t
offset,size_t count);
append(string &str);
append(size_t count, char ch);
append(InputIterator Start,
InputIterator End);

Appends characters to a string from C-style strings, char's or other string objects.

at(size_t offset);

Returns a reference to the character at the specified position. Differs from the
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,


size_t offset);

Copies "count" characters into a C-style string starting at 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);
erase(size_t pos, size_t count);

Erases characters from the specified positions.

Method

Use

find(char ch,size_t offset = 0);


find(char *pt,size_t offset = 0);
find(string &str,size_t offset =
0);

Returns the index of the first character of the substring when found. Otherwise,
the special value "npos" is returned.

find_first_not_of();

Same sets of arguments as find. Finds the index of the first character that is not
in the search string.

find_first_of();

Same sets of arguments as find. Finds the index of the first character that is in
the search string.

find_last_not_of();

Same sets of arguments as find. Finds the index of the last character that is not in
the search string.

find_last_of();

Same sets of arguments as find. Finds the index of the last character that is in the
search string.

insert(size_t pos, char *ptr);


insert(size_t pos, string &str);
insert(size_t pos, size_t count,
char ch);
insert(iterator it, InputIterator
start, InputIterator end);

Inserts characters at the specified position.

push_back(char ch);

Inserts a character at the end of the string.

replace(size_t pos, size_t count,


char *pt);
replace(size_t pos, size_t count,
string &str);
replace(iterator first, iterator
last, char *pt);
replace(iterator first, iterator
last, string &str);

Replaces elements in a string with the specified characters. The range can be
specified by a start position and a number of elements to replace, or by using
iterators.

size();

Returns the number of elements in a string.

swap(string &str);

Swaps two strings.

26

You might also like