string class

22
string Class

Upload: benecia-urban

Post on 31-Dec-2015

33 views

Category:

Documents


0 download

DESCRIPTION

string Class. C-style and C++ string Classes. C-style strings, called C-strings , consist of characters stored in an array ( we’ll look at them later) C++ standard library strings are usable in a manner similar to the built-in types - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: string  Class

string Class

Page 2: string  Class

C-style and C++ string Classes• C-style strings, called C-strings, consist of characters

stored in an array ( we’ll look at them later)

• 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. – Below are some ways C++ strings (variables/objects of type string)

can be used• Note:

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

replace, clear, etc.

Page 3: string  Class

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

• Value assignment at declaration:string mystr(”Hello”); //mystr is initialized to string mystr2=”Hello”; //the string ”Hello” string mystr3(mystr2);

string mystr4(5,’n’); //mystr = “nnnnn”• Assignments from other types are not permitted:

string error1 = ’c’; // error

string error2 = 22; // error

• Can assign a character with assignment operator: mystr=’n’;

String Declaration

Page 4: string  Class

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

cout << s << endl;

• 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 – do not mix one and the other way of input!

String I/O

Page 5: string  Class

• Can use assignment operator as with other types:string s1, s2, s3;

s1=”Intro”;

s2=”OOP”;

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

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

s2= s1 + ’o’;

s2+=’o’;

• No other types can be assigned to strings or concatenated with strings:s2= 42.54; // error

s2=”Catch” + 22; // error

Assignment and Concatenation

Page 6: string  Class

• 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– relying on other ASCII properties (e.g. capital letters are less

than small letters) is bad style

Comparing Strings

Page 7: string  Class

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 8: string  Class

• Number of standard functions are 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()– max_size() - maximum number of characters in string allowed

on this computer– empty() - true if string is empty

• Example:string s=”Hello”;

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

String Functions String Characteristics

Page 9: string  Class

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

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

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

cout << s[6];

• 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

Accessing Elements of Strings

Page 10: string  Class

• 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”

Substrings

Page 11: string  Class

• find family of functions 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– rfind(substring) - same as find, search in reverse– find_first_of(substring) - finds first occurrence of any

character of substring in the string– find_last_of(substring) - finds last occurrence of any

character of substr in the string

• All functions work with individual characters as well:cout << s.find(“l”);

Searching

Page 12: string  Class

• insert(start, substring)- inserts substring starting from position start string s=”place”;

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

• Variant insert(start, number, character) – inserts number of character starting from position start

string s=”place”;

cout << s.insert(4, 2, ’X’);//s= ”placXXe”

– note: ‘x’ is a character not a string

Inserting

Page 13: string  Class

• replace (start, number, substring)- replaces number of characters starting from start with substring – the number of characters replaced need not be the

same

• Examplestring s=”Hello”;s.replace(1,4, ”i, there”); //s is ”Hi, there”

Replacing

Page 14: string  Class

• 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 15: string  Class

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

void myfunc(string s);

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

• If string is not modified by a function, then use const:

void myfunc(const string &s);

Passing Strings as Parameters

Page 16: string  Class

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

• Note: passing strings by value and returning strings is less efficient than passing them by reference

• However, efficiency should in most cases be sacrificed for clarity

Returning Strings

Page 17: string  Class

C-Style string• C-strings are the C language version of strings

• A string may be comprised of 0 or more characters

• A string of 1000 characters requires much more storage than a string of 2 characters

• Thus strings are more complicated than ints

• The C++ standard library provides a string type that hides the details of how the characters are stored

• The C programming language uses arrays of characters

• Note: #include <cstring> is required

Page 18: string  Class

Number of Elements

• There are two ways to keep track of the number of items in an array: – Keep a count of how many items are in the array – Use a marker after the last valid item in the array

• C-strings use a marker

• What is a C-string?– C-string is a null-terminated char array

• The null character is denoted by '\0’• A null occurs after the last character of the string in the

array

Page 19: string  Class

C-string Example• For an initialization using double quotes, "...", the compiler will insert the null

• Except for str2 having more room, the following are all equivalent

char str1[] = “hi!”; //compiler can determine array’s size char str2[20] = “hi!”; //plenty of room char str3[4] = “hi!”; //min size but allows room for null char str4[] = {‘h’,i’,’!’,’\0’};

Page 20: string  Class

C-string Example

• Example of a length function for C-string

int strlength(char mystr[])

{

int count = 0;

while (mystr[count] ! = ‘\0’)

++count;

return count;

}

Page 21: string  Class

C-string Problems• C-strings problems stem from the underlying array

• With C-style strings the programmer must be careful not to access the arrays out of bounds

• Consider string concatenation, combining two strings to form a single

string– Is there room in the destination array for all the characters and the null?

• The C++ string class manages the storage automatically and does not have these problems

Page 22: string  Class

• string_0.cpp • string.cpp • compare.cpp

String Use Examples