- Prof. amr Goneid, AUC
1
CSCE 110 PROGRAMMING FUNDAMENTALS
WITH C++
- Prof. Amr Goneid
WITH C++ Prof. Amr Goneid AUC Part 8. Characters & Strings - - PowerPoint PPT Presentation
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 8. Characters & Strings Prof. amr Goneid, AUC 1 Characters & Strings Prof. amr Goneid, AUC 2 Characters & Strings Characters & their Operations
1
2
3
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
4
5
Conversion (to) Functions:
is Functions: return true or false
6
String Class: Now part of standard library Use #include <string> Strings are “objects” of this class, Member functions
Useful Link:
www.cs.utexas.edu/~jbsartor/cs105/CS105_spr10_lec2.pptx.pdf
7
8
C language has no predefined string data type. It uses character arrays to store strings but appends a
e.g. char bird[ ] = “Eagle”; Some C-Style functions are used on C++ strings after
9
Example: to convert a character array containing digits
Use the c_str member function to convert a string into
10
11
12
Applies member function length and at to string
1st Function returns the objects length 2nd Function returns character at location [i] in
13
14
15
// 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;
16
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;
17
// Display initials cout << "Your initials are " << (firstName.at(0)) << (lastName.at(0)) << endl; return 0; }
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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);
33
// Remove all commas posComma = moneyString.find(","); while (posComma >= 0 && posComma < moneyString.length()) { moneyString.erase(posComma, 1); posComma = moneyString.find(","); } } // end moneyToNumberString
34
35
36
#include <string> #include <iostream> #include <stdlib.h> using namespace std; int main () { string digits; const char *s; int num; cout << "Enter string of digits : "; cin >> digits; s = digits.c_str(); num = atoi(s); cout << num << " " << 2*num << endl; return 0; }