C-strings and C++ string Class

Slides:



Advertisements
Similar presentations
LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Advertisements

C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
Ch 8. Characters and Strings Timothy Budd 2 Characters and Literals Strings Char in C++ is normally an 8-bit quantity, whereas in Java it is a 16-bit.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: More on C-Strings and the string Class Starting Out with.
Lesson 10 Characters, C-Strings, and the string Class CS1 Lesson John Cole1.
Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
Chapter 10.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 12: More About.
CS Nov 2006 C-strings.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 12 More.
String What it is Why it’s useful library routines for handling strings how to input a string from the keyboard.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
1 Chapter 10 Characters, Strings, and the string class.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Chapter 8 Strings and Vectors (8.1 and 8.2). An Array of characters Defined as: char firstName[20]; char firstName[] = {‘T’, ‘i’, ‘m’}; // an array of.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
February 14, 2005 Characters, Strings and the String Class.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: More on C-Strings and the string Class Starting Out with.
Chapter 10. Characters, Strings and the string class Csc 125 Introduction to C++ Fall 2005.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
STARTING OUT WITH STARTING OUT WITH Class 9 Honors.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
Define our own data types We can define a new data type by defining a new class: class Student {...}; Class is a structured data type. Can we define our.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10: Characters, Strings, and the string class.
Characters, Strings, And The string Class Chapter 10.
1 CSE 2341 Object Oriented Programming with C++ Note Set #2.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 10: Characters, C- Strings, and More About.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
CSC 270 – Survey of Programming Languages
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
CS 1430: Programming in C++ 1. Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Chapter Characters, Strings, and the string class 10.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Strings, and the string Class. C-Strings C-string: sequence of characters stored in adjacent memory locations and terminated by NULL character The C-string.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Strings: C-strings vs. Strings as Objects
Characters, Strings, and the cstring Library
C-Strings We have already seen that a C-string is a null-terminated array of characters.
Characters, Strings, and the cstring Library
Characters, C-Strings, and More About the string Class
Chapter 12: More on C-Strings and the string Class
Standard Version of Starting Out with C++, 4th Edition
Object Oriented Programming COP3330 / CGS5409
Strings: C-strings vs. Strings as Objects
10.1 Character Testing.
Standard Version of Starting Out with C++, 4th Edition
C++ Programming Lecture 20 Strings
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

C-strings and C++ string Class

Topics C-Strings Library Functions for Working with C-Strings Conversions Between Numbers and Strings Character Testing Character Case Conversion Writing Your Own C-String Handling Functions C++ string Class

Strings C-string: array of characters terminated by NULL character The C-string "Hi there!" would be stored in memory as shown: H i t h e r e ! \0

Array of char Array of char can be defined and initialized to a C-string char str1[20] = "hi there!"; Array of char can be defined and later have a string copied into it char str2[20]; strcpy(str2, "hi there!"); see pr12-03.cpp

Pointer to char Pointer to char can refer to C-strings defined as arrays of char char str[20] = "hi"; char *pStr = str; cout << pStr; // prints hi Can dynamically allocate memory to be used for C-string using new See Pr12-04.cpp

Library Functions for C-Strings (Requires #include <cstring>) int strlen(char *str) // Returns length of a C-string: cout << strlen("hello"); // Prints: 5

const int LENGTH = 30; char line[LENGTH]; cout << "Enter a string (no more than " << LENGTH - 1 << " characters.)\n"; cin.getline(line, LENGTH); cout << "The C-string read was " << "\"" << line << "\"" << " whose length was " << strlen(line) << endl;

strcpy char name[20] = “Mary” // This is OK char name2[20]; name2 = “Nancy”; // Now allowed char name3[20]; strcpy(name3, “Nancy”); // Copy cout << name3; // Prints Nancy

strcpy strcpy(char *dest, char *source) // Copies a string from a source address // to a destination address char name[15]; strcpy(name, "Deborah"); cout << name; // prints Deborah

strcat strcat(char *dest, char *source) // Takes two C-strings as input. // Adds the contents of the second string to the // end of the first string: char str1[15] = "Good "; char str2[30] = "Morning!"; strcat(str2, str1); cout << str1; // prints: Good Morning! No automatic bounds checking: programmer must ensure that str1 has enough room for result

strcmp int strcmp(char *str1, char*str2) // Compares strings stored at two addresses Returns a value: less than 0 if str1 precedes str2 equal to 0 if str1 equals str2 greater than 0 if str1 succeeds str2 See pr12-06.cpp

strcmp Often used to test for equality if(strcmp(str1, str2) == 0) cout << "equal"; else cout << "not equal"; Also used to determine ordering of C-strings in sorting applications Note that C-strings cannot be compared using == or > if (str1 > str2) -- this is not allowed (compares addresses of C-strings, not contents) If See pr12-05.cpp, pr12-07.cpp, and 12-08.cpp

Swapping const int NAME_LENGTH = 20; char name1[NAME_LENGTH]; char name2[NAME_LENGTH]; char temp[NAME_LENGTH]; strcpy(name1, "William"); strcpy(name2, "Catherine"); cout << "Originally...\n"; cout << "Name1: " << name1 << endl; cout << "Name2: " << name2 << endl;

Swapping (cont.) if (strcmp(name1, name2) > 0) { strcpy(temp, name1); strcpy(name1, name2); strcpy(name2, temp); } cout << "\nAfter switch...\n"; cout << "Name1: " << name1 << endl; cout << "Name2: " << name2 << endl;

Character Testing Requires #include <cctype> FUNCTION MEANING isalpha() true if arg. is a letter, false otherwise isalnum() true if arg. is a letter or digit, false otherwise isdigit() true if arg. is a digit 0-9, false otherwise islower() true if arg. is lowercase letter, false otherwise See pr12-12.cpp, pr12-13.cpp

Character Testing Require #include<cctype> FUNCTION MEANING isprint() true if arg. is a printable character, false otherwise ispunct() true if arg. is a punctuation character, false otherwise isupper() true if arg. is an uppercase letter, false otherwise isspace() true if arg. is a white space character, false otherwise

C++ String Class

The C++ string Class The string class offers several advantages over C-style strings: large body of member functions overloaded operators to simplify expressions Requires #include <string>

string class constructors string(string str) initializes string object with str string(char *cstr) initializes string ojbect with C-string Various other constructors www.cplusplus.com See pr12-18.cpp

String Class Member Functions int find(string str) // returns the position of str in the string object int find (char ch) // returns the position of ch in the string object int find (string str, int x) // returns the position of str beyond x int find (ch ch, intx) // returns the position of ch beyond

String Class Member Functions (cont.) void insert (int x, string str) // inserts str at position x void insert (int x, char ch) // inserts char at position x string replace(int pos, int n, string str) // replaces n characters starting at pos with // substring str Other member functions www.cplusplus.com

Overloaded string Operators MEANING >> reads whitespace-delimited strings into string object << outputs string object to a stream = assigns string on right to string object on left += appends string on right to end of contents of string on left See pr12-19.cpp and pr12-20.cpp

Overloaded string Operators (continued) MEANING + Returns concatenation of the two strings [] references character in string using array notation >, >=, <, <=, ==, != relational operators for string comparison. Return true or false

Overloaded string Operators string word1, phrase; string word2 = " Dog"; cin >> word1; // user enters "Hot" // word1 has "Hot" phrase = word1 + word2; // phrase has // "Hot Dog" phrase += " on a bun"; for (int i = 0; i < 16; i++) cout << phrase[i]; // displays // "Hot Dog on a bun"

Swapping Two Strings string name1 = "William"; string name2 = "Catherine"; string temp; cout << "Originally...\n"; cout << "Name 1: " << name1 << endl; cout << "Name 2: " << name2 << endl; if (name1 > name2){ temp = name1; name1 = name2; name2 = temp; } cout << "\nAfter swap...\n";

Conversion to C-strings data() and c_str() both return the C-string equivalent of a string object Useful when using a string object with a function that is expecting a C-string char greeting[20] = "Have a "; string str("nice day"); strcat(greeting, str.data());

Modification of string objects str.insert(int pos, string s) inserts s at position pos in str Convert constructor for string allows a C-string to be passed in place of s string str("Have a day"); str.insert(7, "nice "); insert is overloaded for flexibility

Modification of string objects str.append(string s) appends contents of s to end of str Convert constructor for string allows a C-string to be passed in place of s string str("Have a "); str.append("nice day"); append is overloaded for flexibility

Your Turn (Formatting Number) Problem: Design a function which formats a string like “1234567.89” to “$1,234,567.89”. Plan: Find the position dp of the decimal point Starting at dp, count backwards and insert a comma every 3 places. At position 0, insert ‘$’.

Refinement dp 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 . 9 dp  position of decimal point in string pos  dp Loop (while dp is greater than 3) go back 3 places in the string insert ‘,’ there End Loop Insert “$” at front of string

Your Turn Write a program which inputs a long text and counts the frequency of occurrence of each letter in the text. letters 1 2 3 4 5 … 23 24 25 frequency 8 1 2 20 3 … 7

In Main() const int MAX = 26; int frequency[MAX]; string text; // Declarations const int MAX = 26; int frequency[MAX]; string text; cout << "Please enter a “ + “substantially long text.\n"; getline(cin, text); string input(text); // convert to // c-string letterFrequency(frequency, MAX, input);

Letter Frequency The quick brown fox jumps over the lazy dog. Pack my box with five dozen liquor jugs. Now is the time for all good people to come to the aid of their country.

letterFrequency() void letterFrequency(int frequency[], int count, string input) { // Initialize requency for (int i = 0; i < count; i++){ frequency[i] = 0; } // Count frequency int length = input.length(); for (int i = 0; i < length; i++) { switch(input[i]) case 'a': case 'A': frequency[0]++; break; case 'b': case 'B': frequency[1]++; break;

letterFrequency() (cont.) case 'c': case 'C': frequency[2]++; break; case 'd': case 'D': frequency[3]++; break; case 'e': case 'E': frequency[4]++; break; . . . . . .; case 'x': case 'X': frequency[23]++; break; case 'y': case 'Y': frequency[24]++; break; case 'z': case 'Z': frequency[25]++; break; default:; } // switch }

String I/O string str1; cin >> str1; // delimitted by // white-space cout << str1; string str2; getline(cin, str2); // delimitted by // by eol

Your Turn Problem: Assumption: Input a long sentence and count the number of words. Assumption: All words are delimitted by a single space.

In Main() // Input text // wordCount = countWords(text) // Output results

countWords() int countWords(string text) Loop (while length > 0 && !done) ps  position of ‘ ‘ in text If (ps = 0) done  true End If Add one to count Replace first part of text with “” End Loop