string Class Cstyle and C string Classes Cstyle

  • Slides: 22
Download presentation
string Class

string Class

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

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.

String Declaration • String declaration: string mystr; //mystr is empty • Value assignment at

String Declaration • String declaration: string mystr; //mystr is empty • Value assignment at declaration: string mystr(”Hello”); //mystr is initialized to mystr 2=”Hello”; //the string ”Hello” mystr 3(mystr 2); mystr 4(5, ’n’); //mystr = “nnnnn” • Assignments from other types are not permitted: string error 1 = ’c’; // error string error 2 = 22; // error • Can assign a character with assignment operator: mystr=’n’;

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

String I/O • 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 worldn – input assigns only hello to s – using getline() function - assigns all characters to string up to newline (not included): getline(cin, s); hello worldn - input assigns hello world to s – do not mix one and the other way of input!

Assignment and Concatenation • Can use assignment operator as with other types: string s

Assignment and Concatenation • Can use assignment operator as with other types: string s 1, s 2, s 3; s 1=”Intro”; s 2=”OOP”; • Plus “+” is used for string concatenation: s 3=s 1 + ”to” + s 2; – at least one operand has to be string variable! • Compound concatenation allowed: s 1 += ”duction”; • Characters can be concatenated with strings: s 2= s 1 + ’o’; s 2+=’o’; • No other types can be assigned to strings or concatenated with strings: s 2= 42. 54; // error s 2=”Catch” + 22; // error

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

Comparing Strings • Comparison operators (>, <, >=, <=, ==, !=) are applicable to strings • Strings are compared lexicographically: string s 1=”accept”, s 2=”access”, s 3=”acceptance”; s 1 is less than s 2 and s 1 is less than s 3 • 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 • Comparison to literal string constants and named constants is also legal:

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 himn”;

String Functions String Characteristics • Number of standard functions are defined for strings. Usual

String Functions String Characteristics • 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

Accessing Elements of Strings • Similar to arrays a character in a string can

Accessing Elements of Strings • 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

Substrings • substr - function that returns a substring of a string: substr(start, numb),

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

Searching • find family of functions return position of substring found, if not found

Searching • 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”);

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

Inserting • 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= ”plac. XXe” – note: ‘x’ is a character not a string

Replacing • replace (start, number, substring)- replaces number of characters starting from start with

Replacing • replace (start, number, substring)- replaces number of characters starting from start with substring – the number of characters replaced need not be the same • Example string s=”Hello”; s. replace(1, 4, ”i, there”); //s is ”Hi, there”

Appending, Erasing • append(string 2)- appends string 2 to the end of the string

Appending, Erasing • append(string 2)- appends string 2 to the end of the 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

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

Passing Strings as Parameters • 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);

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

Returning Strings • 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

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

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

Number of Elements • There are two ways to keep track of the number

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 '’ • A null occurs after the last character of the string in the array

C-string Example • For an initialization using double quotes, ". . . ", the

C-string Example • For an initialization using double quotes, ". . . ", the compiler will insert the null • Except for str 2 having more room, the following are all equivalent char str 1[] = “hi!”; //compiler can determine array’s size str 2[20] = “hi!”; //plenty of room str 3[4] = “hi!”; //min size but allows room for null str 4[] = {‘h’, i’, ’!’, ’’};

C-string Example • Example of a length function for C-string int strlength(char mystr[]) {

C-string Example • Example of a length function for C-string int strlength(char mystr[]) { int count = 0; while (mystr[count] ! = ‘’) ++count; return count; }

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

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

String Use Examples • string_0. cpp • string. cpp • compare. cpp

String Use Examples • string_0. cpp • string. cpp • compare. cpp