350 likes | 567 Vues
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++. Prof. Amr Goneid AUC Part 8. Characters & Strings. Characters & Strings. Characters & Strings. Characters & their Operations The String Class: String Objects Declaration Input and Output Member Functions: Length & Indexing
E N D
CSCE 110PROGRAMMINGFUNDAMENTALSWITH C++ Prof. Amr Goneid AUC Part 8. Characters & Strings Prof. amr Goneid, AUC
Characters & Strings Prof. amr Goneid, AUC
Characters & Strings • Characters & their Operations • The String Class: String Objects • Declaration • Input and Output • Member Functions: Length & Indexing • Copying , Concatenation & Comparison • Other Member Functions • Passing String Objects • Arrays of Strings • Conversions Prof. amr Goneid, AUC
1. Characters & their Operations • Characters: e.g.‘A’ • Character Constants & Variables: e.g.const char qmark = ‘?’ ; char c; • I/O : e.g.cin >> c; cout << c; • Comparison: e.g.(c >= ‘A’) && (c <= ‘Z’) • Character Arrays: e.g.char a[20]; • Type casting: e.g.int(‘A’) char(65) Prof. amr Goneid, AUC
Some Character Manipulation Functions • Conversion (to) Functions:toupper & tolower e.g. char a , b ; b = toupper(a); • isFunctions: return true or false isalpha (A – Z , a – z) isdigit (0 – 9) isalnum (A – Z, a – z , 0 – 9) islower (a – z) isupper (A – Z) Prof. amr Goneid, AUC
2. The String Class: String Objects • String Class: Now part of compiler • Use #include <string> • Strings are “objects” of this class, Member functions can be used • Useful Link: www.cs.utexas.edu/~jbsartor/cs105/CS105_spr10_lec2.pptx.pdf 0 1 2 character length-1 Prof. amr Goneid, AUC
C-Style Strings • C language has no predefined string data type. • It uses character arrays to store strings but appends a null character ‘\0’ at the end of the string. • e.g. char bird[ ] = “Eagle”; • Some C-Style functions are used on C++ strings after converting them to C-style 0 1 2 Prof. amr Goneid, AUC
3. Declaration • String Literals: “Hello” • Constant strings: const string greeting = “Hello ”; • String Objects: string firstName, lastName; string wholeName; string greeting = “Hello “; Prof. amr Goneid, AUC
4. Input & Output • Use extraction operator >> and the stream cin for input ( stops at a blank) cin >> firstName; • Use insertion operator << and the stream cout for output cout << greeting << wholeName << endl; Prof. amr Goneid, AUC
Input & Output getline (cin, wholeName, term); reads all characters typed in from the keyboard (including blanks) up to the character stored interm. Such character will not be added to the string. getline (cin, wholename); will assume the default termination character (end of line or ‘\n’) Prof. amr Goneid, AUC
5. Member Functions:Length & Indexing • Dot notation used to call an objects member functions wholeName.length(); wholeName.at(i) • Applies member functionlength andatto string objectwholeName • 1st Function returns the objects length • 2nd Function returns character at location [i] instring object ( equivalent towholeName [i]) Prof. amr Goneid, AUC
6. Copying , Concatenation & Comparison • Stores the first and last name wholeName = firstName + “ “ + lastName; • Concatenation +joins the two objects together • “ “for string values not ‘ ‘ • Compare two strings using== < > <= >= != if ( myName == wholeName ) ……. Prof. amr Goneid, AUC
Example • Build Inverse String: string aword , invword; cin >> aword; invword = “”; // Null String for (i = aword.length()-1; i >= 0; i--) invword += aword.at(i); cout << invword; Prof. amr Goneid, AUC
StringOperations.cpp • // FILE: StringOperations.cpp • // ILLUSTRATES STRING OPERATIONS • #include <iostream> • #include <string> • using namespace std; • int main () • { • string firstName, lastName; • string wholeName; • string greeting = "Hello "; • cout << "Enter your first name: "; • cin >> firstName; Prof. amr Goneid, AUC
StringOperations.cpp • cout << "Enter your last name: "; • cin >> lastName; • // Join names in whole name • wholeName = firstName + " " + lastName; • // Display results • cout << greeting << wholeName << • '!' << endl; cout << "You have " << • (wholeName.length () - 1) << " letters in your name." << endl; Prof. amr Goneid, AUC
StringOperations.cpp • // Display initials • cout << "Your initials are " << (firstName.at(0)) << (lastName.at(0)) << endl; • return 0; • } Prof. amr Goneid, AUC
StringOperations.cpp Program output Enter your first name: Caryn Enter your last name: Jackson Hello Caryn Jackson! You have 12 letters in your name. Your initials are CJ Prof. amr Goneid, AUC
7. Other Member Functions: .find .append .insert .swap .replace .c_str .erase .assign .substr .empty Prof. amr Goneid, AUC
.find • message.find(c) or message.find(sub) returns position of character (c) or start ofsubstring (sub) inmessage.If (c) or (sub) do not exist inmessage,function returns a long integer > message.length(). e.g. message = “one two three”; message.find(‘e’) returns 2 message.find(“two”) returns 4 Prof. amr Goneid, AUC
.insert • message.insert( s , newstring) returnsmessageafter insertingnewstringstarting at location (s) e.g. message = “abcd”; s1 = “klm”; message.insert(2 , s1); changes message to be “abklmcd” Prof. amr Goneid, AUC
.replace • message.replace(s , n , newstring) returnsmessageafter replacing (n)characters bynewstringstarting at location (s) e.g. message = “during last week”; message.replace(12 , 4 , “month”) changes message to “during last month” Prof. amr Goneid, AUC
Example • Search and replace: p = message.find(sub); if ((p >= 0) && (p < message.length())) message.replace(p,sub.length() , news); else cout << sub << “ not found” << endl; Prof. amr Goneid, AUC
.erase • message.erase(s , n) returnsmessageafter deleting n characters starting at location (s) e.g. message = “one two three”; message.erase(3 , 4) changes message to “one three” Prof. amr Goneid, AUC
.assign • message.assign(olds , s , n) starting at location (s) in olds, assign tomessagethe next n characters. e.g. olds = “abcdef”; message.assign(olds , 2 , 3) changes message to “cde” Prof. amr Goneid, AUC
.substr • message.substr( s , n) return the substring consisting of (n) characters starting at location (s) inmessage e.g. message = “Good Morning”; cout << message.substr(0 , 2); outputs “Go” Prof. amr Goneid, AUC
.empty() • message.empty() returnstrueifmessageis an emptystring,falseotherwise e.g. if (message.empty()) ………. Prof. amr Goneid, AUC
.append(str) • s.append(s1) returnss after appending s1 at its end e.g. if s = “Last”; s.append(“ Month”); changes s to be “Last Month” Prof. amr Goneid, AUC
.swap(str) • s.swap(s1) swaps contents of s and s1 e.g. if s = “First”; s1 = “Second”; s.swap(s1); changes s to be “Second” and s1 to be “First” Prof. amr Goneid, AUC
.c_str() • s.c_str( ) will return a constant character array having the contents of s and terminated by a null character ‘\0’,i.e. a C_style string e.g. const char *cstr; cstr = cppstr.c_str(); Prof. amr Goneid, AUC
8. Passing String Objects • String objects are passed like ordinary variables, i.e., either by value or by reference. • If the string is input only, pass by value, e.g. void doit (string s) • If the string is Output or Inout, pass by reference, e.g. void doit (string& s) Prof. amr Goneid, AUC
Example void moneyToNumberString (string& moneyString) { // Local data . . . int posComma; // position of next comma // Remove $ from moneyString if (moneyString.at(0) == '$') moneyString.erase(0, 1); else if (moneyString.find("-$") == 0) moneyString.erase(1, 1); Prof. amr Goneid, AUC
Example (cont) // Remove all commas posComma = moneyString.find(","); while (posComma >= 0 && posComma < moneyString.length()) { moneyString.erase(posComma, 1); posComma = moneyString.find(","); } } // end moneyToNumberString Prof. amr Goneid, AUC
9. Arrays of Strings • Strings can be elements of arrays. string names[100]; declares an array of 100 strings. • names[i] refers to string [i] in the array. • names[i].at(j) refers to character (j) of string [i]. • names[i] [j] the same as above Prof. amr Goneid, AUC
10. Conversions • A c_string of digits can be converted into a number using one of the following functions: • Atoi(c_string) returns type int • Atol(c_string) returns type long • Atof(c_string) returns type double Prof. amr Goneid, AUC
Conversion Example #include <string> #include <iostream> #include <stdlib.h> using namespace std; int main () { string digits; const char *s; intnum; cout << "Enter string of digits :"; cin >> digits; s = digits.c_str(); num = atoi(s); cout << num << " " << 2*num << endl; return 0; } Prof. amr Goneid, AUC