Presentation is loading. Please wait.

Presentation is loading. Please wait.

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++

Similar presentations


Presentation on theme: "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++"— Presentation transcript:

1 string Class

2 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 is required – There are functions for operations such as insert, erase, replace, clear, etc.

3 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

4 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

5 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

6 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

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

8 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

9 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

10 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

11 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

12 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

13 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” Replacing

14 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

15 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

16 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

17 C++ string Operations Operations

18 C++ string Operations

19 C++ String Operations (more)

20 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 is required

21 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

22 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’};

23 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; }

24 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

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


Download ppt "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++"

Similar presentations


Ads by Google