0% found this document useful (0 votes)
55 views43 pages

Module1 F Cstyle String

The document discusses C++ strings and the string class. It covers: - The objectives of understanding basic string types, defining and using the string class and C-type strings, reading/writing strings, and manipulating characters within a string. - The different string formats including the standard string class which allows treating strings as a basic data type without having to deal with implementation as in C-strings. - Constructors and assignment of strings, and input/output of strings using operators and functions like getline().

Uploaded by

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

Module1 F Cstyle String

The document discusses C++ strings and the string class. It covers: - The objectives of understanding basic string types, defining and using the string class and C-type strings, reading/writing strings, and manipulating characters within a string. - The different string formats including the standard string class which allows treating strings as a basic data type without having to deal with implementation as in C-strings. - Constructors and assignment of strings, and input/output of strings using operators and functions like getline().

Uploaded by

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

Lecture 6

C++ Strings

1
TCP1231 Computer Programming I
Objectives
▪ Understand the basic types of strings.
▪ Define and use the string class and C-type
strings.
▪ Read and write strings.
▪ Access and manipulate characters or sub-
strings within a string.
▪ Concatenate and compare strings.
▪ Insert, replace, swap, or erase a sub-string in
a string.

2
TCP1231 Computer Programming I
String Taxonomy

3
TCP1231 Computer Programming I
String Formats

4
TCP1231 Computer Programming I
The Standard string Class
▪ The string class allows the programmer to
treat strings as a basic data type
▪ No need to deal with the implementation as with
C-strings
▪ The string class is defined in the string library
and the names are in the standard
namespace
▪ To use the string class you need these lines:
#include <string>
using namespace std;
5
TCP1231 Computer Programming I
C++ String

Notes

▪ The extraction operator stops at whitespace.


▪ To read a string with spaces, we must use getline.
▪ The string input /output operators and functions are
defined in the string header file, not the I/O stream
header file

6
TCP1231 Computer Programming I
string Constructors
▪ The default string constructor initializes the
string to the empty string
▪ Another string constructor takes a C-string
argument
▪ Example:
string phrase; // empty string
string noun("ants"); // a string version
//
of "ants"

7
TCP1231 Computer Programming I
#include <iostream>
#include <iomanip>
#include <string> Demonstrate
String
using namespace std;
int main ()
{
string s1;
string s2 ("Hello World");
Constructors
string s3 (s2);
string s4 (5, 'A');
string s5 (s2, 6);
string s6 ("Hello", 2);
string s7 ("Hello", 3, 2); Value of s1:
Value of s2: Hello World
cout << "Value of s1: " << s1 << endl;
Value of s3: Hello World
cout << "Value of s2: " << s2 << endl;
cout << "Value of s3: " << s3 << endl; Value of s4: AAAAA
cout << "Value of s4: " << s4 << endl; Value of s5: World
cout << "Value of s5: " << s5 << endl; Value of s6: He
cout << "Value of s6: " << s6 << endl; Value of s7: lo
cout << "Value of s7: " << s7 << endl;
return 0;
} // main
8
TCP1231 Computer Programming I
string class in C++ Standard Library
#include <iostream>
#include <string>
using namespace std;
int main() {
char cstr[] = "Hi";
string s1,s2;

string s3 = "hello"; must #include <string> and use namespace std


string s4("aloha");
string s5 = cstr;
construct empty string
string s6(cstr);
construct a string based on c-String
string s7(s3);
cout << "[" << s1 << "]" << endl; construct a []
cout << "[" << s2 << "]" << endl; string based on []
cout << "[" << s3 << "]" << endl; another string
[hello]
cout << "[" << s4 << "]" << endl;
cout << "[" << s5 << "]" << endl; [aloha]
cout << "[" << s6 << "]" << endl; [Hi]
cout << "[" << s7 << "]" << endl; [Hi]
}
[hello]
9
TCP1231 Computer Programming I
Assignment of Strings
▪ Variables of type string can be assigned with
the = operator
▪ Example: string s1, s2, s3;

s3 = s2;
▪ Quoted strings are type cast to type string
▪ Example: string s1 = "Hello Mom!";

10
TCP1231 Computer Programming I
When assigning string to a c++ string,
#include <iostream> we do not need to worry about whether
#include <string>
there is enough memory allocated or
using namespace std;
not, the string will automatically adjust
int main() { its size if there is not enough memory
char cstr[] = "Arnold"; allocated.
string s1,s2,s3;

s1 = cstr; assigning c-string into c++ string


s2 = "Schwarzenegger";
s3 = s1; assigning a c++ string into another c++
string
cout << "[" << s1 << "]" << endl;
cout << "[" << s2 << "]" << endl;
[Arnold]
cout << "[" << s3 << "]" << endl;
} [Schwarzenegger]
[Arnold]

We can assign a C-strings or C++ strings directly into a C++


string without needing to use the strcpy() functions as in C-
string. The strcpy() function can only be used with C-strings.

11
TCP1231 Computer Programming I
String
#include <iostream>
#include <string>
using namespace std;

int main ()
Assignment
{
string str1 ("String 1");
string str2;
string str3;
string str4;
string str5 = "String 5";

cout << "String 1: " << str1 << endl;


str2 = str1;
cout << "String 2: " << str2 << endl;
str3 = "Hello"; String 1: String 1
cout << "String 3: " << str3 << endl;
String 2: String 1
str4 = 'A';
cout << "String 4: " << str4 << endl;
String 3: Hello
cout << "String 5: " << str5 << endl; String 4: A
return 0; String 5: String 5
} // main
12
TCP1231 Computer Programming I
I/O With Class string
▪ The insertion operator << is used to output
objects of type string
▪ Example: string s = "Hello Mom!";
cout << s;
▪ The extraction operator >> can be used to
input data for objects of type string
▪ Example: string s1;
cin >> s1;

13
TCP1231 Computer Programming I
getline and Type string
▪ A getline function exists to read entire lines
into a string variable
▪ This version of getline is not a member of the
istream class, it is a non-member function
▪ Syntax for using this getline is different than that
used with cin: cin.getline(…)
▪ Syntax for using getline with string objects:
getline(Istream_Object, String_Object);

14
TCP1231 Computer Programming I
getline Example
▪ This code demonstrates the use of getline with
string objects
▪ string line;
cout "Enter a line of input:\n";
getline(cin, line);
cout << line << "END OF OUTPUT\n";

Output could be:


Enter some input:
Do be do to you!
Do be do to you!END OF OUTPUT

15
TCP1231 Computer Programming I
#include <iostream>
#include <string>
getline
similar to the cin.getline() function to read
using namespace std;
int main() {
characters into C-string from user, however,
string s; for the C++-string, the cin is one of the
parameter of the getline() function.
cout << "=> ";
cin >> s;
cin.ignore(1000,'\n');
cout << s << endl;

cout << "=> ";


getline(cin, s); => how are you? i am fine
cout << s << endl; how
cout << "=> ";
=> how are you? i am fine
getline(cin, s, '?'); how are you? i am fine
cout << s << endl; => how are you? i am fine
}
how are you

16
TCP1231 Computer Programming I
getline
#include <iostream>
#include <iomanip>
#include <string>
#include <conio.c>
using namespace std;

int main ()
{
cout << "Enter Your Name in the form lastname,firstname: ";
string lName;
string fName;
getline (cin, lName, ',');
getline (cin, fName);

cout << "Your Name is: " << fName << " " << lName;
getch();
return 0;
} // main

17
TCP1231 Computer Programming I
More Examples
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <conio.c> #include <conio.c>
using namespace std; using namespace std;

int main () int main ()


{ {
cout << "Enter some words. \n"; cout << "Enter some words. \n";
string strIn; string strIn;
while (cin >> strIn) while (getline(cin, strIn))
cout << strIn << endl; cout << strIn << endl;
cout << “The End"; cout << “The End";
getch(); getch();
return 0; return 0;
} // main } // main

18
TCP1231 Computer Programming I
ignore
▪ ignore is a member of the istream class
▪ ignore can be used to read and discard all the
characters, including '\n' that remain in a line
▪ Ignore takes two arguments
▪ First, the maximum number of characters to discard
▪ Second, the character that stops reading and
discarding
▪ Example: cin.ignore(1000, '\n');
reads up to 1000 characters or to '\n'

19
TCP1231 Computer Programming I
String Processing
▪ The string class allows the same operations
we used with C-strings…and more
▪ Characters in a string object can be accessed as
if they are in an array
▪ last_name[i] provides access to a single character
as in an array
▪ Index values are not checked for validity!

20
TCP1231 Computer Programming I
Member Function at
▪ at is an alternative to using [ ]'s to access
characters in a string.
▪ at checks for valid index values
▪ Example: string str("Mary");
cout << str[6] << endl;
cout << str.at(6) << endl;
str[2] = 'X';
str.at(2) = 'X';

21
TCP1231 Computer Programming I
Member Function length

▪ The string class member function length


returns
the number of characters in the string object:

▪ Example:
int n = string_var.length( );

22
TCP1231 Computer Programming I
Comparison of strings
▪ Comparison operators work with string
objects
▪ Objects are compared using lexicographic order
(Alphabetical ordering using the order of symbols
in the ASCII character set.)
▪ = = returns true if two string objects contain the
same characters in the same order
▪ Remember strcmp for C-strings?
▪ <, >, <=, >= can be used to compare string
objects

23
TCP1231 Computer Programming I
#include <iostream>
#include <string>

String
using namespace std;

int main () {
string str1 ("ABC Company");
string str2 ("ABC");
Comparisons
string str3 ("ABC");

if (str1 == str2)
cout << "str1 == str2" << endl;
if (str1 > str2)
cout << "str1 > str2" << endl;

if (str1 < str2)


cout << "str1 < str2" << endl;

if (str2 == str3)
cout << "str2 == str3" << endl; str1 > str2
str2 == str3
return 0;
} // main

24
TCP1231 Computer Programming I
Using + With strings
(Concatenation)
▪ Variables of type string can be concatenated
with the + operator
▪ Example: string s1, s2, s3;

s3 = s1 + s2;
▪ If s3 is not large enough to contain s1 + s2, more
space is allocated
▪ More specific, use append:
▪ append(string &str, size_t offset, size_t count);
▪ append(string &str);
▪ append(size_t count, char ch);

25
TCP1231 Computer Programming I
#include <iostream>
#include <string>
using namespace std;
String
int main () { Concatenation
string str1 = "This is ";
string str2 = "a string"; This is a string
string str3;
Begin append: This is a string
str3 = str1 + str2;
cout << str3 << endl; Append method: This is a string string
Append characters: This is a string!!!!!
cout << "\nBegin append: ";
str1 = str1 + str2; We can add/concatenate C++
cout << str1 << endl; strings, C-strings or characters
into a C++ string to form a new
str1.append(str2, 1, string::npos); C++ string using the '+' operator
cout << "Append method: " << str1 << endl; w i t hout n e e d i n g t o u s e t h e
strcat() functions as in C-string.
str3.append(5, '!'); The strcat() function can only
cout << "Append characters: " << str3; be used with C-strings.
return 0;
}
26
TCP1231 Computer Programming I
String Extraction
▪ Access the substring of the calling string
starting at position and having length
characters
▪ Format
str.substr(position, length);

27
TCP1231 Computer Programming I
#include <iostream>
#include <string>
using namespace std; String
int main () {
string str1 = "Concatenation";
Extraction
string str2;

cout << "str1 contains: " << str1 << endl;


cout << "str2 contains: " << str2 << endl;
cout << “\t 0123456789012" << endl;

str2 = str1.substr();
cout << "str2 ==> 1: " << str2 << endl;
str1 contains: Concatenation
str2 = str1.substr(5, 3);
cout << "str2 ==> 2: " << str2 << endl;
str2 contains:
0123456789012
str2 = str1.substr(5); str2 ==> 1: Concatenation
cout << "str2 ==> 3: " << str2 << endl;
return 0;
str2 ==> 2: ten
} str2 ==> 3: tenation
28
TCP1231 Computer Programming I
Find string
▪ Format
str.find(str1); returns index of the first occurrence
of str1 in str
str.find(str1, pos);
returns index of the first
occurrence of string str1
in str, the search starts at
position pos.
str.find_first_of(str1, pos);
returns index of the first
instance in str of
any character in str1, starting the search at
position pos.
str.find_first_not_of(str1, pos);
returns index of the first
instance in str of
any character not in str1, starting the
TCP1231 Computersearch at position
Programming I pos. 29
#include <iostream>
#include <string> Find
using namespace std;

int main ()
{
int where;
string str1 = "ccccatenatttt";

where = str1.find("ten");
cout << "\"ten\" at: " << where << endl;

where = str1.find("tin");
if (where != string::npos)
cout << "\"tin\" at: " << where << endl;
else
cout << "\"tin\" not at: " << where << endl;
"ten" at: 5
"tin" not at: -1
return 0;
}
Page 598

30
TCP1231 Computer Programming I
#include <iostream> Find
#include <string>
using namespace std; return the index of the first occurrence of string
int main() {
"be" within s1 starting from position 0.
string s1 = "...to be, or... not to
be!";
string s2 = "be"; return the index of the first occurrence of
string s3;
string "be" within s1 starting from position 8.
s3 = s1.substr(6,13);
cout << s3 << endl;

cout << s1.find(s2) << endl;


cout << s1.find("be") << endl;
cout << s1.find("be",0) << endl;
cout << s1.find("be",8) << endl;

return 0;
} be, or... not
6
6
6
23
31
TCP1231 Computer Programming I
#include <iostream>
#include <string>
Find
using namespace std; returns the index of the
first instance in s1 of any
int main() { character in s2, starting
string s1 = "...to be, or... not to be!";
string s2 = "aeiou"; the search at position 11.
string s3 = ",.!";

cout << s1.find_first_of(s2,0) << endl;


cout << s1.find_first_of(s2,11) << endl;

cout << s1.find_first_not_of(s3,0) << endl;


cout << s1.find_first_not_of(s3,12) << endl;
}

4
17
returns the index of the first
3
instance in s1 of any character
15
NOT in s2, starting the search
at position 12.

32
TCP1231 Computer Programming I
Insert string

▪ Inserts str2 into str beginning at position pos.


str.insert(pos, str2);

▪ Inserts str2, beginning at position start of


length length, into str beginning at position
pos.
str.insert(pos, str2, start, length);

33
TCP1231 Computer Programming I
#include <iostream>
#include <string>
using namespace std; Insertion
int main ()
{
string str1 = "This is Test";
string str2 = "tell me if, are you sure";
cout << "str1 ==>0: " << str1 << endl;

str1.insert(8, "a ");


cout << "str1 ==>1: " << str1 << endl;

str1.insert(14, str2, 10, 14);


cout << "str1 ==>2: " << str1 << endl;

str1 = str1.insert(str1.length(), 3, '?');


cout << "str1 ==>3: " << str1 << endl;

return 0; str1 ==>0: This is Test


} str1 ==>1: This is a Test
str1 ==>2: This is a Test, are you sure
str1 ==>3: IThis is a Test, are you sure???
TCP1231 Computer Programming 34
Replace the string
▪ str1.replace(pos, len, str2);
replace the str1 with str2 beginning at
position pos of length len

▪ str1.replace(pos, len, str2, start, length);


replace the str1, beginning at position
pos of length len, with str2
beginning at position
start of length length

35
TCP1231 Computer Programming I
#include <iostream>
#include <string> Replacement
using namespace std;

int main () {
string str1 = "My Name was Omar Ahmad";
string str2 = "My Last Name is Zaqaibeh";

cout << "str1 ==>0: " << str1 << endl;

str1.replace(8, 3, "is");
cout << "str1 ==>1: " << str1 << endl;
str1 ==>0: My Name was Omar Ahmad
str1 ==>1: My Name is Omar Ahmad
str1.replace(15, 6, str2, 15, 9);
str1 ==>2: My Name is Omar Zaqaibeh
cout << "str1 ==>2: " << str1 << endl;
str1 ==>3: What is Your Name?
str1.replace(0, str1.length(), "What is Your Name?");
cout << "str1 ==>3: " << str1 << endl;
return 0;
}
36
TCP1231 Computer Programming I
#include <iostream>
#include <string>
using namespace std; Erase,
Clear, and
int main () {
string str1 = "This is one string";
string str3;

cout << "str1 ==>0: " << str1 << endl; Empty
str3 = str1;
str1.erase();
cout << "str1 ==>1: " << str1 << endl; str1 ==>0: This is one string
if (str1.empty()) str1 ==>1:
cout <<"\n\tstr1 is empty \n\n";
str1 = str3; str1 is empty
str1.erase(8, 4);
cout << "str1 ==>2: " << str1 << endl;
str1 = str3; str1 ==>2: This is string
str1.clear(); str1 ==>3:
cout << "str1 ==>3: " << str1 << endl;
if (str1.empty()) str1 is empty
cout <<"\n\tstr1 is empty \n";
return 0;
} 37
TCP1231 Computer Programming I
Swap the two strings
▪ swap(str1, str2);
interchange the string str1 with str2

▪ Example:
▪ Before swapping
str1 = “Multimedia” str2 = “University”
▪ After swapping
str1 = “University” str2 = “Multimedia”

38
TCP1231 Computer Programming I
#include <iostream>
#include <string> Swap
#include <conio.c>
using namespace std;

int main ()
{
string str1 = "read then eat";
string str2 = "eat then sleep";

cout << "str1 ==>0: " << str1 << endl;


cout << "str2 ==>0: " << str2 << endl;

cout << endl;


swap(str1, str2); str1 ==>0: read then eat
cout << "str1 ==>1: " << str1 << endl;
str2 ==>0: eat then sleep
cout << "str2 ==>1: " << str2 << endl;
str1 ==>1: eat then sleep
return 0;
}
str2 ==>1: read then eat

39
TCP1231 Computer Programming I
string Objects to C-strings
▪ Recall the automatic conversion from C-string
to string: char a_c_string[] = "C-string";
string_variable = a_c_string;

▪ strings are not converted to C-strings


▪ Both of these statements are illegal:
▪ a_c_string = string_variable;
▪ strcpy(a_c_string, string_variable);

40
TCP1231 Computer Programming I
Converting strings to C-strings
▪ The string class member function c_str
returns the C-string version of a string object
▪ Example:
strcpy(a_c_string, string_variable.c_str( ) );

▪ This line is still illegal


a_c_string = string_variable.c_str( );
▪ Recall that operator = does not work with C-
strings

41
TCP1231 Computer Programming I
Conversion between C-string and C++ string
valid, assign a C-string to
char cstr[20] = "hello";
C++ string
string cppstr = "world";

cppstr = cstr;
Invalid, can not assign nor
cstr = cppstr; copy a C++-string to C
strcpy(cstr, cppstr); string.

strcpy(cstr, cppstr.c_str() );
valid, convert a C++-string to C
string (using the c_str()
cstr = cppstr.c_str() ; function) before it is being copy
into the C-string

Invalid, even though the C++-string has been convert to C-string, we can
not assign the new C-string into another C-string, we need to use the
strcpy() for that.

42
TCP1231 Computer Programming I
The End

43
TCP1231 Computer Programming I

You might also like