computer programming- lecture 6

43
1 TCP1231 Computer Programming I Lecture 6 C++ Strings

Upload: dr-md-shohel-sayeed

Post on 20-Jan-2015

6.644 views

Category:

Education


0 download

DESCRIPTION

C++ Strings

TRANSCRIPT

Page 1: Computer Programming- Lecture 6

1TCP1231 Computer Programming I

Lecture 6C++ Strings

Page 2: Computer Programming- Lecture 6

2TCP1231 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.

Page 3: Computer Programming- Lecture 6

3TCP1231 Computer Programming I

String Taxonomy

Page 4: Computer Programming- Lecture 6

4TCP1231 Computer Programming I

String Formats

Page 5: Computer Programming- Lecture 6

5TCP1231 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;

Page 6: Computer Programming- Lecture 6

6TCP1231 Computer Programming I

Notes

C++ String

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

Page 7: Computer Programming- Lecture 6

7TCP1231 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"

Page 8: Computer Programming- Lecture 6

8TCP1231 Computer Programming I

#include <iostream>#include <iomanip>#include <string>using namespace std;int main (){

string s1;string s2 ("Hello World");string s3 (s2);string s4 (5, 'A');string s5 (s2, 6);string s6 ("Hello", 2);string s7 ("Hello", 3, 2);

cout << "Value of s1: " << s1 << endl;cout << "Value of s2: " << s2 << endl;cout << "Value of s3: " << s3 << endl;cout << "Value of s4: " << s4 << endl;cout << "Value of s5: " << s5 << endl;cout << "Value of s6: " << s6 << endl;cout << "Value of s7: " << s7 << endl;return 0;

} // main

Value of s1: Value of s2: Hello WorldValue of s3: Hello WorldValue of s4: AAAAAValue of s5: WorldValue of s6: HeValue of s7: lo

Demonstrate String Constructors

Page 9: Computer Programming- Lecture 6

9TCP1231 Computer Programming I

#include <iostream>#include <string>using namespace std;int main() { char cstr[] = "Hi"; string s1,s2;

string s3 = "hello"; string s4("aloha"); string s5 = cstr; string s6(cstr);

string s7(s3); cout << "[" << s1 << "]" << endl; cout << "[" << s2 << "]" << endl; cout << "[" << s3 << "]" << endl; cout << "[" << s4 << "]" << endl; cout << "[" << s5 << "]" << endl; cout << "[" << s6 << "]" << endl; cout << "[" << s7 << "]" << endl;}

[][][hello][aloha][Hi][Hi][hello]

construct a string based on c-String

construct empty string

construct a string based on another string

must #include <string> and use namespace std

string class in C++ Standard Library

Page 10: Computer Programming- Lecture 6

10TCP1231 Computer Programming I

Assignment of Strings

Variables of type string can be assigned withthe = operator Example: string s1, s2, s3;

… s3 = s2;

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

Page 11: Computer Programming- Lecture 6

11TCP1231 Computer Programming I

#include <iostream>#include <string>using namespace std;

int main() { char cstr[] = "Arnold"; string s1,s2,s3; s1 = cstr; s2 = "Schwarzenegger"; s3 = s1; cout << "[" << s1 << "]" << endl; cout << "[" << s2 << "]" << endl; cout << "[" << s3 << "]" << endl;}

[Arnold][Schwarzenegger][Arnold]

assigning c-string into c++ string

assigning a c++ string into another c++ string

When assigning string to a c++ string, we do not need to worry about whether there is enough memory allocated or not, the string will automatically adjust its size if there is not enough memory allocated.

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.

Page 12: Computer Programming- Lecture 6

12TCP1231 Computer Programming I

#include <iostream>#include <string>using namespace std;

int main () {

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";cout << "String 3: " << str3 << endl;str4 = 'A';cout << "String 4: " << str4 << endl;cout << "String 5: " << str5 << endl;return 0;

} // main

String Assignment

String 1: String 1String 2: String 1String 3: HelloString 4: AString 5: String 5

Page 13: Computer Programming- Lecture 6

13TCP1231 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;

Page 14: Computer Programming- Lecture 6

14TCP1231 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);

Page 15: Computer Programming- Lecture 6

15TCP1231 Computer Programming I

getline Example

This code demonstrates the use of getline withstring 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

Page 16: Computer Programming- Lecture 6

16TCP1231 Computer Programming I

#include <iostream>#include <string>

using namespace std;int main() { string s;

cout << "=> "; cin >> s; cin.ignore(1000,'\n'); cout << s << endl; cout << "=> "; getline(cin, s); cout << s << endl; cout << "=> "; getline(cin, s, '?'); cout << s << endl;}

=> how are you? i am finehow=> how are you? i am finehow are you? i am fine=> how are you? i am finehow are you

similar to the cin.getline() function to read characters into C-string from user, however, for the C++-string, the cin is one of the parameter of the getline() function.

getline

Page 17: Computer Programming- Lecture 6

17TCP1231 Computer Programming I

#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

Enter Your Name in the form lastname,firstname: Azli, FikriYour Name is: Fikri Azli

getline

Page 18: Computer Programming- Lecture 6

18TCP1231 Computer Programming I

#include <iostream>#include <string>#include <conio.c>using namespace std;

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

#include <iostream>#include <string>#include <conio.c>using namespace std;

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

More Examples

Page 19: Computer Programming- Lecture 6

19TCP1231 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'

Page 20: Computer Programming- Lecture 6

20TCP1231 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!

Page 21: Computer Programming- Lecture 6

21TCP1231 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';

Page 22: Computer Programming- Lecture 6

22TCP1231 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( );

Page 23: Computer Programming- Lecture 6

23TCP1231 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

Page 24: Computer Programming- Lecture 6

24TCP1231 Computer Programming I

#include <iostream>#include <string>using namespace std;

int main () { string str1 ("ABC Company"); string str2 ("ABC"); 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;

return 0;

} // main

str1 > str2str2 == str3

String Comparisons

Page 25: Computer Programming- Lecture 6

25TCP1231 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);

Page 26: Computer Programming- Lecture 6

26TCP1231 Computer Programming I

#include <iostream>#include <string>using namespace std;

int main () {string str1 = "This is "; string str2 = "a string";string str3;

str3 = str1 + str2;cout << str3 << endl;

cout << "\nBegin append: ";str1 = str1 + str2;cout << str1 << endl;

str1.append(str2, 1, string::npos);cout << "Append method: " << str1 << endl;

str3.append(5, '!');cout << "Append characters: " << str3;return 0;

}

This is a string

Begin append: This is a stringAppend method: This is a string stringAppend characters: This is a string!!!!!

String Concatenation

We can add/concatenate C++ strings, C-strings or characters into a C++ string to form a new C++ string using the '+' operator without needing to use the strcat() functions as in C-string. The strcat() function can only be used with C-strings.

Page 27: Computer Programming- Lecture 6

27TCP1231 Computer Programming I

String Extraction

Access the substring of the calling string starting at position and having length characters

Format str.substr(position, length);

Page 28: Computer Programming- Lecture 6

28TCP1231 Computer Programming I

#include <iostream>#include <string>using namespace std;

int main () {string str1 = "Concatenation";string str2;

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

str2 = str1.substr();cout << "str2 ==> 1: " << str2 << endl;

str2 = str1.substr(5, 3);cout << "str2 ==> 2: " << str2 << endl;

str2 = str1.substr(5);cout << "str2 ==> 3: " << str2 << endl;return 0;

}

str1 contains: Concatenationstr2 contains: 0123456789012

str2 ==> 1: Concatenationstr2 ==> 2: tenstr2 ==> 3: tenation

String Extraction

Page 29: Computer Programming- Lecture 6

29TCP1231 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

search at position pos.

Page 30: Computer Programming- Lecture 6

30TCP1231 Computer Programming I

#include <iostream>#include <string>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;

return 0;}

"ten" at: 5"tin" not at: -1

Find

Page 598

Page 31: Computer Programming- Lecture 6

31TCP1231 Computer Programming I

#include <iostream>#include <string>using namespace std;

int main() { string s1 = "...to be, or... not to

be!"; string s2 = "be"; string s3; 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... not66623

return the index of the first occurrence of string "be" within s1 starting from position 0.

return the index of the first occurrence of string "be" within s1 starting from position 8.

Find

Page 32: Computer Programming- Lecture 6

32TCP1231 Computer Programming I

#include <iostream>#include <string>using namespace std;

int main() { string s1 = "...to be, or... not to be!"; string s2 = "aeiou"; 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;}

417315

returns the index of the first instance in s1 of any character in s2, starting the search at position 11.

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

Find

Page 33: Computer Programming- Lecture 6

33TCP1231 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);

Page 34: Computer Programming- Lecture 6

34TCP1231 Computer Programming I

#include <iostream>#include <string>using namespace std;

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 Teststr1 ==>1: This is a Teststr1 ==>2: This is a Test, are you surestr1 ==>3: This is a Test, are you sure???

Insertion

Page 35: Computer Programming- Lecture 6

35TCP1231 Computer Programming I

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

Page 36: Computer Programming- Lecture 6

36TCP1231 Computer Programming I

#include <iostream>#include <string>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.replace(15, 6, str2, 15, 9); cout << "str1 ==>2: " << str1 << endl;

str1.replace(0, str1.length(), "What is Your Name?"); cout << "str1 ==>3: " << str1 << endl; return 0;}

str1 ==>0: My Name was Omar Ahmadstr1 ==>1: My Name is Omar Ahmadstr1 ==>2: My Name is Omar Zaqaibehstr1 ==>3: What is Your Name?

Replacement

Page 37: Computer Programming- Lecture 6

37TCP1231 Computer Programming I

#include <iostream>#include <string>using namespace std;int main () { string str1 = "This is one string";

string str3;

cout << "str1 ==>0: " << str1 << endl;str3 = str1;str1.erase();cout << "str1 ==>1: " << str1 << endl;if (str1.empty())

cout <<"\n\tstr1 is empty \n\n";str1 = str3;str1.erase(8, 4);cout << "str1 ==>2: " << str1 << endl;str1 = str3;str1.clear();cout << "str1 ==>3: " << str1 << endl;if (str1.empty())

cout <<"\n\tstr1 is empty \n";return 0;

}

str1 ==>0: This is one stringstr1 ==>1:

str1 is empty

str1 ==>2: This is stringstr1 ==>3:

str1 is empty

Erase, Clear, andEmpty

Page 38: Computer Programming- Lecture 6

38TCP1231 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”

Page 39: Computer Programming- Lecture 6

39TCP1231 Computer Programming I

#include <iostream>#include <string>#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);

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

return 0;}

str1 ==>0: read then eatstr2 ==>0: eat then sleep

str1 ==>1: eat then sleepstr2 ==>1: read then eat

Swap

Page 40: Computer Programming- Lecture 6

40TCP1231 Computer Programming I

string Objects to C-strings

Recall the automatic conversion from C-stringto 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);

Page 41: Computer Programming- Lecture 6

41TCP1231 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

Page 42: Computer Programming- Lecture 6

42TCP1231 Computer Programming I

Conversion between C-string and C++ string

char cstr[20] = "hello"; string cppstr = "world";

cppstr = cstr;

cstr = cppstr; strcpy(cstr, cppstr);

strcpy(cstr, cppstr.c_str() );

cstr = cppstr.c_str() ;

valid, assign a C-string to C++ string

Invalid, can not assign nor copy a C++-string to C string.

valid, convert a C++-string to C string (using the 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.

Page 43: Computer Programming- Lecture 6

43TCP1231 Computer Programming I

The End