Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t...
-
Upload
maryam-goodkind -
Category
Documents
-
view
218 -
download
2
Transcript of Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t...
Lecture 24:Strings
2
Lecture Contents:
Library functions Assignment and substrings Concatenation Comparison Demo programs Exercises
3
Strings basics
Definition: Symbolic or Non numeric data
– symbols (sole /single/ characters)
– strings (sequence of characters)
4
Characters and strings in C
Character literal ‘A’
Character variables char a, b = ’x’; Character input a=getchar(); scanf(“%c”, &a);
Character output putchar(b); printf(“%c”, b);
String literal “A” “AUBG”String variables char c[10], d[20], e[]= ”Sofia”;String input gets(c); scanf(“%s”, d);String output puts(e); printf(“%s”, e);
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
A A 065 65 00x41 0x41 0x00
Usually Strings are null-terminated.
6
Characters and strings in C
How to declare and initialize string variables
char v1[30];
char v2[10] = “Sofia”;
char v3[] = “AUBG”;
7
NO Operators on string variables – functions
(#include <string.h>) are to be used instead
strcpy Makes a copy of sourcevoid strcpy(char *dest, const char *source);
strncpy Makes a copy of up to n characters from sourcevoid strncpy(char *dest, const char *source, unsigned n);
strcat Appends source to the end of destvoid strcat(char *dest, const char *source);
strncat Appends up to n characters from source to the end of destvoid strncat(char *dest, const char *source, unsigned n);
8
NO Operators on string variables – functions
(#include <string.h>) 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 s2int strncmp(const char *s1, const char *s2, unsigned n);
strlen Returns the number of characters in sint strlen(const char *s);
9
Characters and strings in C++ based on STL
Character literal ‘A’Character variables char a, b=’x’;Character input cin >> a;Character output cout << b;
String literal “AUBG”String variables string c, d = “Sofia”;String input cin >> c;String output cout << d;
10
Operators on string variables – header file (#include <string>)
Concatenation
string firstname = “Caryn”;
string lastname = “Jackson”;
string wholename;
wholename = firstname + “ “ + lastname;
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
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
More on strings
Extract from Friedman/Koffman, sub chapters 3.7, 9.9
14
3.7 Extending C++ through Classes
– Discuss classes• String class part of compiler
– #include <string>
15
String Class
Declaring string objects Reading & Displaying strings Assignment & Concatenation Operator Overloading Dot Notation Member Functions Object Assignments
16
Declaring string Objects
A number of ways to declare
string firstName, lastName;
string wholeName;
string greeting = “Hello “;
17
Reading & Displaying string Objects
Use extraction operator >> with the stream cin for input from the keyboardcin >> firstName;
Use insertion operator << with the stream cout for output to the screencout << greeting << wholeName << endl;
18
Reading & Displaying string Objects
getline(cin, lastName, ‘\n’);
reads all characters typed in from the keyboard (cin – 1st argument) up to the new line (3rd argument) into the string object (lastName) specified as second argument
19
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; cout << "Enter your last name: ";cin >> lastName;
// Join names in whole name wholeName = firstName + " " + lastName;
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
StringOperations.cpp
Program outputEnter your first name: Caryn
Enter your last name: Jackson
Hello Caryn Jackson!
You have 12 letters in your name.
Your initials are CJ
22
Assignment
Stores the first and last name– wholeName = firstName + “ “ + lastName;
Concatenation– to join the two objects together use +
Attention: “ “ for string values not ‘ ‘
23
Operator Overloading
+ normally means addition but with strings it means concatenation
The + can take on many meanings– Operator Overloading– C++ can have multi meanings to 1 operator– >> & << are overloaded operators– * / - == = all can be overloaded
24
Dot Notation
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
Exercise 23.1
Build programs based on strings:
To display a string char by char on a new line each;
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
Exercise 23.1
Build programs based on strings:
Implementing your own version of strlen or strcpy or strcat library functions;
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
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
Exercise 23.1
Build programs based on strings:
Implementing a function to test a character string being a palindrome or not.
31
Before lecture end
Lecture:
Strings
More to read:
Friedman/Koffman, sub Chapters 3.7, 9.9
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
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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 34
Accessing the String Library
• Must include the appropriate library
#include <string>
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 35
String Objects
• Attributes include– character sequence it stores– length
• Common operations<< >> = +
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 36
Listing 3.16 Illustrating string operations
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 37
Listing 3.16 Illustrating string operations (continued)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 38
Declaring string Objects
• General declarations format:
type identifier1, identifier2, . . .;
• E.g.:
string firstName, lastName;
string wholeName;
string greeting = “Hello “;
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’);
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
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
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
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).
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 44
Additional Member Functions
• Searching for a stringwholeName.find(firstName)
• Inserting characters into a stringwholeName.insert(0, “Ms.”);
• Deleting portion of a stringwholeName.erase(10,4);
• Assign a substring to a string objecttitle.assign(wholeName, 0, 3);
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
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 )
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
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
Thank You
For
Your Attention