1 / 22

string Class

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

Download Presentation

string Class

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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

  3. String Declaration • 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’;

  4. 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 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!

  5. Assignment and Concatenation • 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

  6. Comparing Strings • 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

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

  8. 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

  9. 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

  10. 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”

  11. 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”);

  12. 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= ”placXXe” • note: ‘x’ is a character not a string

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

  14. Appending, Erasing • 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

  15. 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);

  16. 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

  17. 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

  18. 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

  19. 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’};

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

  21. 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

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

More Related