26
string Class Mohamed Shehata 1020: Introduction to Programming

String Class Mohamed Shehata 1020: Introduction to Programming

Embed Size (px)

Citation preview

Page 1: String Class Mohamed Shehata 1020: Introduction to Programming

string Class

Mohamed Shehata1020: Introduction to Programming

Page 2: String Class Mohamed Shehata 1020: Introduction to Programming

Classes

• Classes are the next higher (above functions) level of modularization in C++

• Among other things, classes give us a technique for implementing new data types and operations on them (data abstraction).

• Many useful classes are already defined in class libraries and in this course the focus is on how to use a class, in particular the string class.

Page 3: String Class Mohamed Shehata 1020: Introduction to Programming

C++ string Classes• C++ standard library strings are usable in a manner similar to

the built-in types– Remember, a variable's/object's type determines what operations may

be performed on it.

• Note:– #include <string> is required – There are functions for operations such as insert, erase,

replace, clear, etc.

Page 4: String Class Mohamed Shehata 1020: Introduction to Programming

• String declaration: string myName; //mystr is empty

• Value assignment at declaration:string myName(”Mohamed”); //myName is initialized to string myName2=”Mohamed”; //the string ”Mohamed” string myName3(myName2);

string mystr(5,’n’); //mystr = “nnnnn”• myName, myName2, myName3, and mystr are called objects

of the string class

String Declaration

Page 5: String Class Mohamed Shehata 1020: Introduction to Programming

String Assignment

• I can assign strings to different values string myName = “John Smith"; //initialization

myName = “Mohamed Shehata"; //assignmnet

• The object myName is now Mohamed Shehata, the original John Smith is not there anymore

• Assignments from other types are not permitted:string error1 = ’c’; // error - character

string error2 = 22; // error - integer

Page 6: String Class Mohamed Shehata 1020: Introduction to Programming

string s1, s2, s3;

s1=”1020”;

s2=”Introduction to Programming”;

• Plus “+” is used for string concatenation: s3=s1 + ”-” + s2;– at least one operand has to be string variable!

So S3 now is “1020-Introduction to Programming”

• Compound concatenation allowed: s1 += ”course”; • Only Characters can be concatenated with strings:

s2= s1 + ’o’;

s2+=’o’;

Concatenation

Page 7: String Class Mohamed Shehata 1020: Introduction to Programming

• String can be output as any other type:string s=”hello world”;

cout << s << endl;

The output on your screen is: hello world

• Two ways to input strings:– using extraction operator - strips white space and assigns

the first “word” to the string:cin >> s;

hello world\n – input assigns only hello to s – using getline() function - assigns all characters to string

up to newline (not included): getline(cin, s);

hello world\n - input assigns hello world to s

String I/O

Page 8: String Class Mohamed Shehata 1020: Introduction to Programming

• Comparison operators (>, <, >=, <=, ==, !=) are applicable to strings

• Strings are compared lexicographically:string s1=”accept”, s2=”access”, s3=”acceptance”;

s1 is less than s2 and s1 is less than s3

• Order of symbols is determined by the symbol table (ASCII)– letters in the alphabet are in the increasing order– longer word (with the same characters) is greater than

shorter word

Comparing Strings

Page 9: String Class Mohamed Shehata 1020: Introduction to Programming

Comparing Strings• Comparison to literal string constants and named constants is also

legal:

const string myname=”John Doe”;

string hername=”Jane Doe”;

if ((myname==hername)||(myname==”Jake Doe”))

cout << ”found him\n”;

Page 10: String Class Mohamed Shehata 1020: Introduction to Programming

• There are a number of functions defined for strings. Usual syntax:string_name.function_name(arguments)

• Useful functions return string parameters:– size() - current string size (number of characters currently

stored in string– length()- same as size()– empty() - true if string is empty

• Example:string s=”Hello”;

cout << s.length(); // outputs 5

String Functions String Characteristics

Page 11: String Class Mohamed Shehata 1020: Introduction to Programming

Characters in a string

• Characters in a string are actually stored in an array

string s=”C++ Program”;

C + + P r o g r a m

s

s[0] s[s.length()-1]

Page 12: String Class Mohamed Shehata 1020: Introduction to Programming

• Similar to arrays a character in a string can be accessed and assigned to using its index (start from 0) cout << str[3];

• CAREFUL: Could be an error to access an element beyond the size of the string:

string s=”Hello”; // size is 5

cout << s[6]; // error

• Type of the element of the string is character, assigning integers, strings and other types are not allowed s[3] = ”hi”; // compilation error

s[3] = 22; // depends on compiler which

//might interpret is as ASCII code

Accessing Elements of Strings

Page 13: String Class Mohamed Shehata 1020: Introduction to Programming

• find function return position of substring found, if not found return global constant string::npos defined in string header– find(substring) - returns the position of the first character

of substring in the string– If not found then it retruns string::npos – npos is a static member constant value with the greatest

possible value for an element of type size_t.• All functions work with individual characters as well:

Ex: string s1="acceptance";

unsigned int pos = s1.find("q");

if(pos != string::npos)

cout<< pos;

else

cout<<"not found";

Searching

Page 14: String Class Mohamed Shehata 1020: Introduction to Programming

Searching

• Let’s use another format to find the second occurrence string problem = "Great Meal";

int pos = problem.find("a"); //return 3

pos = problem.find("a", pos +1);

• This will cause the search to start immediately after the pos of the first a (that is at 4) and so will return 8 ( thereby resetting pos to 8).

Page 15: String Class Mohamed Shehata 1020: Introduction to Programming

• substr - function that returns a substring of a string: substr(start, numb), where start - index of the first character,

numb - number of characters

• Example:string s=”Hello”; // size is 5

cout << s.substr(3,2); // outputs ”lo”

• Example:string s=”This is cool”;

string sub_s=s.substr(8,4);

cout << sub_s; // outputs ”cool”

Substrings

Page 16: String Class Mohamed Shehata 1020: Introduction to Programming

• insert(start, substring)- inserts substring starting from position start

string s=”place”;

cout << s.insert(1, ”a”); // s=”palace”

Inserting

Page 17: String Class Mohamed Shehata 1020: Introduction to Programming

• append(string2)- appends string2 to the end of the string

string s=”Hello”;

cout << s.append(”, World!”);

cout << s; // outputs ”Hello, World!”

• erase(start, number)- removes number of characters starting from start

string s=”Hello”;

s.erase(1,2);

cout << s; // outputs ”Hlo”• clear()- removes all characters

s.clear(); // s becomes empty

Appending, Erasing

Page 18: String Class Mohamed Shehata 1020: Introduction to Programming

• Strings can be passed as parameters:– by value:

void myfunc(string s);

– by reference:void myfunc(string &s);

Passing Strings as Parameters

Page 19: String Class Mohamed Shehata 1020: Introduction to Programming

• Strings (unlike arrays) can be returned:– string myfunc(int, int);

string lastName (){

string last; // write code here to extract last name

return last;

}

Returning Strings

Page 20: String Class Mohamed Shehata 1020: Introduction to Programming

Examples From Previous ExamsExamples From Previous Exams

Page 21: String Class Mohamed Shehata 1020: Introduction to Programming

• Write a function to permanently erase all white spaces in a string starting at certain position. For example:string problem = " Test 1020";removeSpaces(problem,0);cout<<problem;

Outputs:“Test 1020”

void removeSpaces(string &line, int pos){

while( line[pos] == ' ') // 'space' line.erase(pos,1);}

Page 22: String Class Mohamed Shehata 1020: Introduction to Programming

• Write a function to parse email addresses that separated by a semi colon (;). The function should do the following:– remove all leading white spaces– Return the number of emails found in the string– Put the individual emails in an array

• This function will not handle situations of an empty email line and will not handle situation of an extra semicolon at the end

• For example: s=“[email protected]; [email protected]”The function will fill the array emails as follows:emails[0]=“[email protected]”emails[1]=“[email protected]

• Here is the prototype of the function:

int parseEmail(string line, string emails [] )

Page 23: String Class Mohamed Shehata 1020: Introduction to Programming

int parseEmail(string line, string emails [] ) { int number=0; int start = 0; unsigned int next; do{ removeSpaces(line,start); next = line.find(";", start); if (next != string::npos) { emails[number] = line.substr(start, next-start); start = next + 1; // start past the space number++; } else { emails[number] = line.substr(start, line.length()-start); number++;

} } while (next != string::npos);

return number;}

Page 24: String Class Mohamed Shehata 1020: Introduction to Programming

• Note that there are many other special cases not handled• This is ok as this code is meant to show you only a

concept of using strings

Page 25: String Class Mohamed Shehata 1020: Introduction to Programming

Final F2013

hogwarts

Page 26: String Class Mohamed Shehata 1020: Introduction to Programming

Spring 2013What is the output of calling bar(3);

void bar(int b){ const int n=10; string s="3▼▼nisupif"; // ▼ is empty space for (int i=n*b; i>0; i-=b) cout<<s[i%n];}

3pi is fun