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.
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 is required – There are functions for operations such as insert, erase, replace, clear, etc.
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
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
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
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
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
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”;
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
Characters in a string Characters in a string are actually stored in an array string s=”C++ Program”; C++Program s s[0] s[s.length()-1]
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
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
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).
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
insert(start, substring) - inserts substring starting from position start string s=”place”; cout << s.insert(1, ”a”); // s=”palace” Inserting
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
Strings can be passed as parameters: – by value: void myfunc(string s); – by reference: void myfunc(string &s); Passing Strings as Parameters
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
Examples From Previous Exams
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); }
Write a function to parse addresses that separated by a semi colon (;). The function should do the following: – remove all leading white spaces – Return the number of s found in the string – Put the individual s in an array This function will not handle situations of an empty line and will not handle situation of an extra semicolon at the end For example: The function will fill the array s as follows: Here is the prototype of the function: int parse (string line, string s [] )
int parse (string line, string s [] ) { int number=0; int start = 0; unsigned int next; do{ removeSpaces(line,start); next = line.find(";", start); if (next != string::npos) { s[number] = line.substr(start, next-start); start = next + 1; // start past the space number++; } else { s[number] = line.substr(start, line.length()-start); number++; } } while (next != string::npos); return number; }
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
Final F2013 hogwarts
Spring 2013 What 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