Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 215 Lecture 6 Strings (Based on Lecture 17 from Ohio State university. Found in http://web.cse.ohio-state.edu/~mengn/Lectures/) An Equal Opportunity.

Similar presentations


Presentation on theme: "CS 215 Lecture 6 Strings (Based on Lecture 17 from Ohio State university. Found in http://web.cse.ohio-state.edu/~mengn/Lectures/) An Equal Opportunity."— Presentation transcript:

1 CS 215 Lecture 6 Strings (Based on Lecture 17 from Ohio State university. Found in An Equal Opportunity University

2 C Strings

3 Types of Strings String Literals: “Hello World” “xyz 123 *&^#$!”
C-style strings: char s[20]; C++ class string; string s;

4 literalString.cpp int main() { char s[] = "Hello World";
... int main() { char s[] = "Hello World"; cout << s << endl; for (int i = 0; i < 11; i++) { cout << s[i] << ","; } cout << endl;

5 literalString.cpp > literalString.exe Hello World
... char s[] = "Hello World"; cout << s << endl; for (int i = 0; i < 11; i++) { cout << s[i] << ","; } cout << endl; > literalString.exe Hello World H,e,l,l,o, ,W,o,r,l,d,

6 Literal String To create a variable containing a literal string:
char s[] = “Hello World”; char s[] means an array of characters; This variable cannot be changed, i.e., the following will generate a syntax error: s = “Goodbye World”; // Syntax Error

7 ascii.cpp ... int main() { char s[] = "Hello World";
cout << s << endl; for (int i = 0; i < 11; i++) { cout << setw(4) << s[i] << ","; } cout << endl; { cout << setw(4) << int(s[i]) << ","; } return 0; }

8 > ascii.exe Hello World H, e, l, l, o, , W, o, r, l, d,
... char s[] = "Hello World"; cout << s << endl; for (int i = 0; i < 11; i++) { cout << setw(4) << s[i] << ","; } cout << endl; { cout << setw(4) << int(s[i]) << ","; } > ascii.exe Hello World H, e, l, l, o, , W, o, r, l, d, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, >

9 null Character Literal strings end in a null character: ‘\0’. (Character ‘\0’ has ASCII code 0.) char s[] = “Hello World”; s[0] equals ‘H’; s[1] equals ‘e’; . . . s[8] equals ‘r’; s[9] equals ‘l’; s[10] equals ‘d’; s[11] equals ‘\0’;

10 literalString2.cpp ... int i; char s[] = "Hello World";
cout << s << endl; i = 0; while(s[i] != '\0') { cout << s[i] << ","; i++; } cout << endl; cout << "s[" << i << "] = " << int(s[i]) << endl;

11 literalString2.cpp > literalString2.exe Hello World
cout << s << endl; i = 0; while(s[i] != '\0') { cout << s[i] << ","; i++; } cout << endl; cout << "s[" << i << "] = " << int(s[i]) << endl; > literalString2.exe Hello World H,e,l,l,o, ,W,o,r,l,d, s[11] = 0

12 ascii2.cpp ... i = 0; while(s[i] != '\0') {
cout << setw(4) << s[i] << ","; i++; } cout << endl; cout << setw(4) << int(s[i]) << ","; cout << setw(4) << int(s[i]);

13 ... i = 0; while(s[i] != '\0') { cout << setw(4) << int(s[i]) << ","; i++; } cout << setw(4) << int(s[i]); cout << endl; > ascii2.exe Hello World H, e, l, l, o, , W, o, r, l, d, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 0 >

14 C-style strings const int MAX_LENGTH(20);
A C-style string is stored in an array of char; C-style strings should always end in ‘\0’; const int MAX_LENGTH(20); char s[MAX_LENGTH] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'}; cout << "String = " << s << endl;

15 cString.cpp // C-style strings should always end in '\0'
const int MAX_LENGTH(20); // C-style strings should always end in '\0' char s[MAX_LENGTH] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'}; cout << "String = " << s << endl; s[1] = 'o'; s[2] = 'w'; s[3] = 'd'; s[4] = 'y'; s[5] = '\0';

16 cString.cpp > cString.exe String = Hello World String = Howdy World
const int MAX_LENGTH(20); // C-style strings should always end in '\0' char s[MAX_LENGTH] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'}; cout << "String = " << s << endl; s[1] = 'o'; s[2] = 'w'; s[3] = 'd'; s[4] = 'y'; s[5] = '\0'; > cString.exe String = Hello World String = Howdy World String = Howdy

17 Literal String A literal string variable cannot be changed, i.e., the following will generate a syntax error: char s[] = “Hello World”; s = “Goodbye World”; // Syntax Error However, individual characters within the string can be changed: s[1] = 'o'; s[2] = 'w'; A literal string should ALWAYS contain ‘\0’.

18 Capitalize Change all characters in a string to capitals.
Input: Hello World Output: HELLO WORLD

19 ASCII Code Code Char 32 Space 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' 40 (
41 ) Code Char 48 49 1 50 2 51 3 52 4 53 5 54 6 55 7 56 8 57 9 Code Char 65 A 66 B 67 C 68 D 69 E 70 F 71 G 72 H 73 I 74 J Code Char 97 a 98 b 99 c 100 d 101 e 102 f 103 g 104 h 105 i 106 j

20 capitalize.cpp ... char s[] = "Hello World"; int ascii_code(0);
int i(0); cout << s << endl; i = 0; while(s[i] != '\0') { ascii_code = int(s[i]); if (97 <= ascii_code && ascii_code <= 122) { ascii_code = ascii_code-32; } cout << char(ascii_code); i++; } cout << endl;

21 > capitalize.exe Hello World HELLO WORLD … i = 0;
while(s[i] != '\0') { ascii_code = int(s[i]); if (97 <= ascii_code && ascii_code <= 122) { ascii_code = ascii_code-32; } cout << char(ascii_code); i++; } > capitalize.exe Hello World HELLO WORLD

22 (Major) Problems with C-style Strings
const int MAX_LENGTH(20); char s[MAX_LENGTH] = { 'H', 'e', 'l', 'l', 'o', '\0'}; cout << "String = " << s << endl; Forgetting to end the string with ‘\0’; Not allocating enough memory for the string; How do you add an element to a string? How do you delete an element from a string? How do you concatenate two strings?

23 C++ Strings

24 C++ class string C++ class string requires: #include <string>
using namespace std; To create a variable of type string, simply: string lastName; Assignment, as always is the same: lastName = “Marx”; Or combine the two with an initialization: string lastName(“Marx”); Or string lastname = “Marx”;

25 String Operators: Assignment
Assignment (=): As with before, assign a string to a variable of type string. string lastName(“Marx”), anothername; anothername = lastName; Both now hold “Marx”

26 String Operators: Concatentation
Concatenation (+): Puts a string on the end of another. string firstName(“Groucho”); string lastName(“Marx”); string fullname = firstName + lastname;

27 concatString.cpp #include <iostream>
#include <string> // < Note using namespace std; int main() { string name1("Groucho“), name2(“Harpo”); string lastName("Marx“); string fullName1 = name1 + lastName; string fullName2 = name2 + lastName; cout << fullName1 << endl; cout << fullName2 << endl;

28 concatString.cpp #include <iostream>
#include <string> // < Note ... { string name1("Groucho“), name2(“Harpo”); string lastName("Marx“); string fullName1 = name1 + lastName; string fullName2 = name2 + lastName; cout << fullName1 << endl; cout << fullName2 << endl; > concatString.exe GrouchoMarx HarpoMarx

29 concatString2.cpp #include <iostream>
#include <string> // < Note using namespace std; int main() { string name1("Groucho“), name2(“Harpo”); string lastName("Marx“); // separate first and last names with a blank string fullName1 = name1 + " " + lastName; string fullName2 = name2 + " " + lastName; cout << fullName1 << endl; cout << fullName2 << endl;

30 concatString2.cpp #include <iostream>
#include <string> // < Note ... { string name1("Groucho“), name2(“Harpo”); string lastName("Marx“); // separate first and last names with a blank string fullName1 = name1 + " " + lastName; string fullName2 = name2 + " " + lastName; cout << fullName1 << endl; cout << fullName2 << endl; > concatString.exe Groucho Marx Harpo Marx

31 C++ String I/O

32 Input/Output with Strings
I/O with Strings are as before: string lastName; cout << “Please enter your last name: “; cin >> lastName; // get the last name cout << “Your last name is “ << lastName;

33 getName.cpp #include <iostream> #include <string>
using namespace std; int main() { string firstName, lastName, fullName; cout << "Enter your first name: "; cin >> firstName; cout << "Enter your last name: "; cin >> lastName; // concatenate fullName = firstName + " " + lastName; cout << "Your name is: " << fullName << endl;

34 getName.cpp > getName.exe Enter your first name: Groucho
string firstName, lastName, fullName; cout << "Enter your first name: "; cin >> firstName; cout << "Enter your last name: "; cin >> lastName; // concatenate fullName = firstName + " " + lastName; cout << "Your name is: " << fullName << endl; > getName.exe Enter your first name: Groucho Enter your last name: Marx Your name is: Groucho Marx

35 getName2.cpp #include <iostream> #include <string>
using namespace std; int main() { string fullName; cout << "Enter your full name: "; cin >> fullName; cout << "Your name is: " << fullName << endl; return 0; }

36 getName2.cpp > getName2.exe Enter your full name: Groucho Marx
... string fullName; cout << "Enter your full name: "; cin >> fullName; cout << "Your name is: " << fullName << endl; > getName2.exe Enter your full name: Groucho Marx Your name is: Groucho

37 Input/Output with Strings
A common problem with reading strings from user input is that it could contain white spaces. cin uses white space (e.g. space, tab, newline) as a delimiter between inputs; cin >> fullName; > getName2.exe Enter your full name: Groucho Marx Your name is: Groucho

38 String I/O: getline() Fortunately, the string class let’s us get around this with the getline() function. Syntax: getline(source, destination) source is the source of the string. In our case, we want cin here. destination is the string variable where we want the string to be read into.

39 String I/O: getline() We can fix our code by rewriting it as follows:
string fullname; cout << “Enter your full name: ”; getline(cin, fullname);

40 getName3.cpp #include <iostream> #include <string>
using namespace std; int main() { string fullName; cout << "Enter your full name: "; getline(cin, fullName); // < Note cout << "Your name is: " << fullName << endl; return 0; }

41 getName3.cpp > getName3.exe Enter your full name: Groucho Marx
... cout << "Enter your full name: "; getline(cin, fullName); // < Note cout << "Your name is: " << fullName << endl; > getName3.exe Enter your full name: Groucho Marx Your name is: Groucho Marx Enter your full name: Groucho G. Marx III Your name is: Groucho G. Marx III

42 getName3.cpp > getName3.exe Enter your full name: Groucho Marx
... cout << "Enter your full name: "; getline(cin, fullName); // < Note cout << "Your name is: " << fullName << endl; > getName3.exe Enter your full name: Groucho Marx Your name is: Groucho Marx Enter your full name: Your name is:

43 literalError.cpp (BAD CODE)
... int main() { char firstName[10], lastName[10]; cout << "Enter first name: "; // DO NOT DO THIS. THIS IS VERY, VERY BAD! cin >> firstName; cout << "Enter last name: "; cin >> lastName; cout << "Your name is: " << firstName << " " << lastName << endl; return 0; }

44 Enter last name: MacGhilleseatheanaich
... char firstName[10], lastName[10]; cout << "Enter first name: "; // DO NOT DO THIS. THIS IS VERY, VERY BAD! cin >> firstName; cout << "Enter last name: "; cin >> lastName; cout << "Your name is: " << firstName << " " << lastName << endl; > literalError.exe Enter first name: John Enter last name: MacGhilleseatheanaich Your name is: naich MacGhilleseatheanaich >

45 C++ String Processing

46 str[k] s[k] represents the k’th character in string s:
string s(“Hello World”); // the character ‘H’ will be output. cout << s[0] << endl; // the character ‘W’ will be output. cout << s[6] << endl;

47 String Processing (2) s[k] represents the (k+1)’st character in string s: string s(“Hello World”); s[1] = ‘o’; s[2] = ‘w’; s[3] = ‘d’; s[4] = ‘y’; // output “Howdy World” cout << s << endl;

48 Relational String Operators
== != < <= > >= == and != are same as before, but the others are not exactly like usage with numbers… For instance, what exactly does it mean if one string is “less than” another?

49 relationOps.cpp ... string s1, s2;
cout << "Enter first string: "; getline(cin, s1); cout << "Enter second string: "; getline(cin, s2); if (s1 == s2) { cout << s1 << " equals " << s2 << endl; } else if (s1 < s2) cout << s1 << " < " << s2 << endl; else cout << s1 << " > " << s2 << endl;

50 relationOps.cpp > relationOps.exe Enter first string: hello
if (s1 == s2) { cout << s1 << " equals " << s2 << endl; } else if (s1 < s2) cout << s1 << " < " << s2 << endl; else cout << s1 << " > " << s2 << endl; > relationOps.exe Enter first string: hello Enter last string: howdy hello < howdy

51 relationOps.cpp > relationOps.exe Enter first string: hello
if (s1 == s2) { cout << s1 << " equals " << s2 << endl; } else if (s1 < s2) cout << s1 << " < " << s2 << endl; else cout << s1 << " > " << s2 << endl; > relationOps.exe Enter first string: hello Enter last string: Howdy hello > Howdy

52 relationOps.cpp > relationOps.exe Enter first string: Hello
if (s1 == s2) { cout << s1 << " equals " << s2 << endl; } else if (s1 < s2) cout << s1 << " < " << s2 << endl; else cout << s1 << " > " << s2 << endl; > relationOps.exe Enter first string: Hello Enter last string: Hello World (What will be the output?)

53 relationOps.cpp Blanks matter: > relationOps.exe
Enter first string: HelloWorld Enter last string: Hello World HelloWorld > Hello World

54 sortNames.cpp ... int main() { const int MAX_SIZE(50);
string name[MAX_SIZE]; int num_names(0), i(0); string s; // Read names i = 0; cout << "Enter name: "; cin >> s; while (s != ".“ && i < MAX_SIZE) name[i] = s; i++; } num_names = i;

55 sortNames.cpp (2) ... // Sort names
for (int i = num_names-1; i > 0; i--) { // Compare name[j] with name[i], j < i for (int j = 0; j < i; j++) if (name[j] > name[i]) swap(name[j], name[i]); } // name[i] is now in its correct location

56 sortNames.cpp (3) ... // Output names cout << endl;
cout << "Names in alphabetic order:" << endl; for (int i = 0; i < num_names; i++) { cout << name[i] << endl; } return 0;

57 String Processing In addition to giving us a new data type to hold strings, the string library offers many useful string processing methods. You can find most of them of them in the book, but here are a few useful ones.

58 String Processing Length() substr(index, n) replace(index, n, str)
insert(index, str)

59 length() This method returns the integer length of the string. (Note: Parentheses “()” after length().) Example: string s1(“Super!”); //the integer 6 will be output. cout << s1.length() << endl;

60 easyFrench.cpp int main() { string s;
cout << "Enter phrase in English: "; getline(cin, s); for (int i = 0; i < s.length(); i++) if (s[i] == 's') { s[i] = 'z'; } else if (s[i] == 'w') { s[i] = 'v'; cout << "French version: "; cout << s << endl; ...

61 substr(index, n) Returns the string consisting of n characters starting from the specified index. Example: string transport(“Cruise Ship”); //outputs “Ship” cout << transport.substr(7, 4) << endl;

62 replace(index, n, str) Removes n characters in the string starting from the specified index, and inserts the specified string, str, in its place. Example: string transport(“Speed Boat”); transport.replace(0, 5, “Sail”); // outputs “Sail Boat” cout << transport << endl;

63 advancedFrench.cpp // example of using C++ class string
#include <iostream> #include <string> using namespace std; int main() { string s; cout << "Enter phrase in English: "; getline(cin, s);

64 advancedFrench.cpp ... for (int i = 0; i < s.length(); i++) {
if (s[i] == 's') s[i] = 'z'; } else if (s[i] == 'w') s[i] = 'v'; else if (s.substr(i, 5) == " the ") s.replace(i, 5, " la "); cout << "French version: "; cout << s << endl; return 0;

65 insert(index, str) Inserts the specified string at the specified index. Example: string animal(“Hippo”); animal.insert(0, “Happy ”); //outputs “Happy Hippo” cout << animal << endl;

66 outputFileName.cpp // construct an output file name from the input file name #include <iostream> #include <string> using namespace std; int main() { string input_filename, output_filename; int length(0); cout << "Enter input file name: "; cin >> input_filename; ...

67 outputFileName.cpp ... length = input_filename.length();
output_filename = input_filename; if (input_filename.substr(0,2) == "in") { output_filename.replace(0,2,"out"); } else output_filename.insert(0, "out."); cout << "Output file name: " << output_filename << endl; return 0;

68 CanadianError.cpp ... int main() { string s;
cout << "Enter phrase in English: "; getline(cin, s); for (int i = 0; i < s.length(); i++) if (s[i] == '.' || s[i] == '?') s.replace(i, 1, ", eh?"); } cout << "Canadian version: "; cout << s << endl; return 0;

69 Canadian.cpp ... int main() { string s;
cout << "Enter phrase in English: "; getline(cin, s); for (int i = 0; i < s.length(); i++) if (s[i] == '.' || s[i] == '?') s.replace(i, 1, ", eh?"); i = i + 4; // Why 4? } cout << "Canadian version: "; cout << s << endl; return 0;

70 Literal vs. C++ strings Literal strings end in a null character: ‘\0’. (Character ‘\0’ has ASCII code 0.) char s[] = “Hello World”; s[11] equals ‘\0’; C++ strings DO NOT end in a null character: ‘\0’. string s2(“Hello World”); s2[11] DOES NOT exist!

71 Passing Strings to Functions

72 outputFileName.cpp ... length = input_filename.length();
output_filename = input_filename; if (input_filename.substr(0,2) == "in") { output_filename.replace(0,2,"out"); } else output_filename.insert(0, "out."); cout << "Output file name: " << output_filename << endl;

73 Function construct_output_filename()
void construct_output_filename (string & in_name, string & out_name) { out_name = in_name; if (in_name.substr(0,2) == "in") out_name.replace(0,2,"out"); } else out_name.insert(0, "out.");

74 outputFileName2.cpp ... void construct_output_filename
(string & in_name, string & out_name); int main() { string input_filename, output_filename; cout << "Enter input file name: "; cin >> input_filename; construct_output_filename(input_filename, output_filename); cout << "Output file name: " << output_filename << endl; return 0; } // Define function construct_output_filename here.

75 Pass Strings by Reference
Strings are complicated objects of arbitrarily large size. Usually strings should be passed by reference (string &).

76 Function construct_output_filename()
void construct_output_filename (const string & in_name, string & out_name) { out_name = in_name; if (in_name.substr(0,2) == "in") out_name.replace(0,2,"out"); } else out_name.insert(0, "out.");

77 outputFileName3.cpp ... void construct_output_filename
(const string & in_name, string & out_name); int main() { string input_filename, output_filename; cout << "Enter input file name: "; cin >> input_filename; construct_output_filename(input_filename, output_filename); cout << "Output file name: " << output_filename << endl; return 0; } // Define function construct_output_filename here.

78 Pass Strings by Reference
Strings are complicated objects of arbitrarily large size. Usually strings should be passed by reference (string &). Strings which should not be modified in the function should be passed as constants (const string &).

79 outputFileNameError.cpp ... void construct_output_filename
(string & in_name, string & out_name); int main() { string output_filename; construct_output_filename(“indata1.txt”, output_filename); cout << "Output file name: " << output_filename << endl; return 0; } (string & in_name, string & out_name)

80 outputFileName4.cpp ... void construct_output_filename
(const string & in_name, string & out_name); int main() { string output_filename; construct_output_filename(“indata1.txt”, output_filename); cout << "Output file name: " << output_filename << endl; return 0; } (const string & in_name, string & out_name)

81 Pass Strings by Reference
Strings are complicated objects of arbitrarily large size. Usually strings should be passed by reference (string &). Strings which should not be modified in the function should be passed as constants (const string &). Literal strings may be passed by reference to constant parameters (const string &).


Download ppt "CS 215 Lecture 6 Strings (Based on Lecture 17 from Ohio State university. Found in http://web.cse.ohio-state.edu/~mengn/Lectures/) An Equal Opportunity."

Similar presentations


Ads by Google