Download presentation
Presentation is loading. Please wait.
Published byMaryam Goodkind Modified over 9 years ago
1
Lecture 24: Strings
2
2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises
3
3 Strings basics Definition: Symbolic or Non numeric data – symbols (sole /single/ characters) – strings (sequence of characters)
4
4 Characters and strings in C Character literal‘A’ Character variableschar a, b = ’x’; Character inputa=getchar();scanf(“%c”, &a); Character outputputchar(b);printf(“%c”, b); String literal“A”“AUBG” String variableschar c[10], d[20], e[]= ”Sofia”; String inputgets(c);scanf(“%s”, d); String outputputs(e);printf(“%s”, e);
5
5 Characters and strings in C Character literal‘A’ String literal“A” Internal memory representation – ASCII ( 1 byte/char) The difference btw ‘A’and “A” ‘A’ occupies 1 byte“A” occupies 2 bytes AA0 65650 0x410x410x00 Usually Strings are null-terminated.
6
6 Characters and strings in C How to declare and initialize string variables char v1[30]; char v2[10] = “Sofia”; char v3[] = “AUBG”;
7
7 NO Operators on string variables – functions (#include ) are to be used instead strcpy Makes a copy of source void strcpy(char *dest, const char *source); strncpy Makes a copy of up to n characters from source void strncpy(char *dest, const char *source, unsigned n); strcat Appends source to the end of dest void strcat(char *dest, const char *source); strncat Appends up to n characters from source to the end of dest void strncat(char *dest, const char *source, unsigned n);
8
8 NO Operators on string variables – functions (#include ) are to be used instead strcmp Compares s1 and s2 alphabetically: <0, if s1 precede s2; 0 if both strings are equal; >0, if s2 precede s1 int strcmp(const char *s1, const char *s2); strncmp Compares the first n characters of s1 and s2 int strncmp(const char *s1, const char *s2, unsigned n); strlen Returns the number of characters in s int strlen(const char *s);
9
9 Characters and strings in C++ based on STL Character literal‘A’ Character variableschar a, b=’x’; Character inputcin >> a; Character outputcout << b; String literal“AUBG” String variablesstring c, d = “Sofia”; String inputcin >> c; String outputcout << d;
10
10 Operators on string variables – header file (#include ) Concatenation string firstname = “Caryn”; string lastname = “Jackson”; string wholename; wholename = firstname + “ “ + lastname;
11
11 Some member functions in the string class getline(cin, aString, ‘\n’) Extracts data characters up to (but not including) the first newline character from stream cin and stores them in aString. aString.length() Returns the count of characters (an integer) in aString. aString.at(i) Returns the character at position i of aString where the leftmost character is at position 0 and the rightmost character is at position aString.length() – 1. aString.find(target) Returns the starting position (an integer) of string target in aString. If target is not in aString, returns a value outside the range of valid positions.
12
12 Some member functions in the string class aString.insert(start, newString) Inserts newString at position start of aString. aString.replace(start, count, newString) Starting at position start of aString, replaces the next count characters with newString. aString.erase(start, count) Starting at position start of aString, removes the next count characters. aString.assign(oldString, start, count) Starting at position start of oldString, assigns to aString the next count characters.
13
13 More on strings Extract from Friedman/Koffman, sub chapters 3.7, 9.9
14
14 3.7 Extending C++ through Classes –Discuss classes String class part of compiler –#include
15
15 String Class t Declaring string objects t Reading & Displaying strings t Assignment & Concatenation t Operator Overloading t Dot Notation t Member Functions t Object Assignments
16
16 Declaring string Objects t A number of ways to declare string firstName, lastName; string wholeName; string greeting = “Hello “;
17
17 Reading & Displaying string Objects Use extraction operator >> with the stream cin for input from the keyboard cin >> firstName; Use insertion operator << with the stream cout for output to the screen cout << greeting << wholeName << endl;
18
18 Reading & Displaying string Objects getline(cin, lastName, ‘\n’); reads all characters typed in from the keyboard (cin – 1 st argument) up to the new line (3 rd argument) into the string object (lastName) specified as second argument
19
19 StringOperations.cpp // FILE: StringOperations.cpp // ILLUSTRATES STRING OPERATIONS #include using namespace std; int main () { string firstName, lastName; string wholeName; string greeting = "Hello "; cout > firstName; cout > lastName; // Join names in whole name wholeName = firstName + " " + lastName;
20
20 StringOperations.cpp // Display results cout << greeting << wholeName << '!' << endl; cout << "You have " << (wholeName.length() - 1) << " letters in your name." << endl; // Display initials cout << "Your initials are " <<(firstName.at(0)) << (lastName.at(0)) << endl; return 0; }
21
21 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
22
22 Assignment t Stores the first and last name –wholeName = firstName + “ “ + lastName; t Concatenation –to join the two objects together use + t Attention: “ “ for string values not ‘ ‘
23
23 Operator Overloading t + normally means addition but with strings it means concatenation t The + can take on many meanings –Operator Overloading –C++ can have multi meanings to 1 operator –>> & << are overloaded operators –*/-=== all can be overloaded
24
24 Dot Notation t Dot notation used to call object’s member functions wholeName.length(); –Applies member function length to string object wholeName –Function returns the object’s length –Table lists some additional functions
25
25 Exercise 23.1 Build programs based on strings: t To display a string char by char on a new line each;
26
26 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void main() { int I=0; cout << endl << str << endl; while (str[I] != ‘\0’) { cout << endl << str[I]; I++; }
27
27 Exercise 23.1 Build programs based on strings: t Implementing your own version of strlen or strcpy or strcat library functions;
28
28 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; int strlenm(char m[]); void main() { cout << endl << strlenm(str) << endl; } int strlenm(char m[]) { int I=0, len; while (m[I] != 0x00) I++; len = I; return len; }
29
29 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void copym(char dst[], char src[]); void main() { char newstr[20]; copym(newstr, str); cout << endl << newstr << endl; } void copym(char dst[], char src[]) { int I=0; while(( dst[I] = src[I] ) != ‘\0’)I++; }
30
30 Exercise 23.1 Build programs based on strings: t Implementing a function to test a character string being a palindrome or not.
31
31 Before lecture end Lecture: Strings More to read: Friedman/Koffman, sub Chapters 3.7, 9.9
32
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3, Section 3.7: Extending C++ through Classes, the string class Problem Solving, Abstraction, and Design using C++ 5e by Frank L. Friedman and Elliot B. Koffman
33
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 33 Using Class string Data abstraction –facilitated in C++ through class feature –enables programmers to define new types –defines a set a values and a set of operations
34
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 34 Accessing the String Library Must include the appropriate library #include
35
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 35 String Objects Attributes include –character sequence it stores –length Common operations > = +
36
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 36 Listing 3.16 Illustrating string operations
37
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 37 Listing 3.16 Illustrating string operations (continued)
38
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 38 Declaring string Objects General declarations format: type identifier 1, identifier 2,...; E.g.: string firstName, lastName; string wholeName; string greeting = “Hello “;
39
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 39 Reading and Displaying Strings Extraction operator is defined for strings cin >> firstName; // reads up to blank or return Insertion operator is defined for strings cout << greetings << wholeName << ‘!’ << endl; Can read string with blanks getline(cin, lastName, ;\n’);
40
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 40 String Assignment and Concatenation + puts strings together (concatenates) E.g.: wholeName = firstName + “ “ + lastName; Note need for space between names
41
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 41 Operator Overloading Note use of + –usually means addition for two numeric values –has been redefined (overloaded) to also mean concatenation when applied to two strings Useful when defining new types
42
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 42 Accessing String Operations Member functions length and at These functions can be called using dot notation Applies the identified operation to the named object E.g.: wholeName.length( ) returns the length of the string currently stored in the variable wholeName
43
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 43 Dot Notation Syntax:object.function-call Ex:firstName.at(0) this returns the character in firstName that is at position 0 (start numbering characters from left, beginning at 0).
44
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 44 Additional Member Functions Searching for a string wholeName.find(firstName) Inserting characters into a string wholeName.insert(0, “Ms.”); Deleting portion of a string wholeName.erase(10,4); Assign a substring to a string object title.assign(wholeName, 0, 3);
45
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9, Section 9.9: Strings As Arrays of Characters Problem Solving, Abstraction, and Design using C++ 5e by Frank L. Friedman and Elliot B. Koffman
46
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 46 Strings and Arrays of Characters string object uses an array of char Can reference individual character of a string object in different ways –name[ i ] –name.at( i ) Other member functions of string class –message.length( i )
47
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 47 9.9 String as Arrays of Characters Declaring and initializing char name[ ] = “Jackson”; // array size 8 or char name[8] = “Jackson”; // 7 characters Last character stored is ‘\0’ to denote the end of the string in a character array
48
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 48 Reading and Writing Character Arrays Can read or write entire character array at once cin >> name; cout << name << endl; Can read or write each character of of array –must account for null character at end of array
49
49 Thank You For Your Attention
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.