49
Lecture 24: Strings

Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

Embed Size (px)

Citation preview

Page 1: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

Lecture 24:Strings

Page 2: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

2

Lecture Contents:

Library functions Assignment and substrings Concatenation Comparison Demo programs Exercises

Page 3: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

3

Strings basics

Definition: Symbolic or Non numeric data

– symbols (sole /single/ characters)

– strings (sequence of characters)

Page 4: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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);

Page 5: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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.

Page 6: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

6

Characters and strings in C

How to declare and initialize string variables

char v1[30];

char v2[10] = “Sofia”;

char v3[] = “AUBG”;

Page 7: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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);

Page 8: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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);

Page 9: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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;

Page 10: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

10

Operators on string variables – header file (#include <string>)

Concatenation

string firstname = “Caryn”;

string lastname = “Jackson”;

string wholename;

 

wholename = firstname + “ “ + lastname;

Page 11: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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.

Page 12: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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.

Page 13: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

13

More on strings

Extract from Friedman/Koffman, sub chapters 3.7, 9.9

Page 14: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

14

3.7 Extending C++ through Classes

– Discuss classes• String class part of compiler

– #include <string>

Page 15: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

15

String Class

Declaring string objects Reading & Displaying strings Assignment & Concatenation Operator Overloading Dot Notation Member Functions Object Assignments

Page 16: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

16

Declaring string Objects

A number of ways to declare

string firstName, lastName;

string wholeName;

string greeting = “Hello “;

Page 17: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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;

Page 18: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 19: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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;

Page 20: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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;}

Page 21: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 22: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

22

Assignment

Stores the first and last name– wholeName = firstName + “ “ + lastName;

Concatenation– to join the two objects together use +

Attention: “ “ for string values not ‘ ‘

Page 23: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 24: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 25: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

25

Exercise 23.1

Build programs based on strings:

To display a string char by char on a new line each;

Page 26: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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++;

}}

Page 27: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

27

Exercise 23.1

Build programs based on strings:

Implementing your own version of strlen or strcpy or strcat library functions;

Page 28: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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;

}

Page 29: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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++;

}

Page 30: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

30

Exercise 23.1

Build programs based on strings:

Implementing a function to test a character string being a palindrome or not.

Page 31: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

31

Before lecture end

Lecture:

Strings

More to read:

Friedman/Koffman, sub Chapters 3.7, 9.9

Page 32: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 33: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 34: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 34

Accessing the String Library

• Must include the appropriate library

#include <string>

Page 35: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 35

String Objects

• Attributes include– character sequence it stores– length

• Common operations<< >> = +

Page 36: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 36

Listing 3.16 Illustrating string operations

Page 37: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 37

Listing 3.16 Illustrating string operations (continued)

Page 38: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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 “;

Page 39: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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’);

Page 40: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 41: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 42: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 43: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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).

Page 44: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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);

Page 45: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 46: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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 )

Page 47: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 48: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

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

Page 49: Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises

49

Thank You

For

Your Attention