In this chapter, you will learn about: An Array Type for Strings. The Standard string Class. Vectors. Introduction Computer Science 1 CS 23021

Similar documents
Copyright 2003 Pearson Education, Inc. Slide 1

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

Chapter 9. Strings. 國立雲林科技大學資訊工程研究所張傳育 (Chuan Yu Chang ) 博士

Engineering Problem Solving with C++, Etter

Ch 6-8. C-Strings. April 30, Prof. Young-Tak Kim

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

BITG 1113: Array (Part 2) LECTURE 9

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Chapter 7: User-Defined Simple Data Types, Namespaces, and the string Type

Chapter 10 Characters, Strings, and the string class

Name. CPTR246 Spring '17 (100 total points) Exam 2

LECTURE 15. String I/O and cstring library

C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018

Lecture 12. We have already used strings. Strings. Hello Class is a string.

Unit 2: The string class

C-String Library Functions

Object Oriented Programming COP3330 / CGS5409

Chapter 10: Character Testing. From Program Character Case Conversion 8/23/2014. Character Testing. Character Case Conversion

Chapter 10: Characters, C- Strings, and More About the string Class

CS 103 Lab - Party Like A Char Star

Chapter 10: Characters, C- Strings, and More About the string Class Character Testing

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Strings in C++ Dr. Ferdin Joe John Joseph Kamnoetvidya Science Academy

CS 103 Lab 6 - Party Like A Char Star

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

Lecture 3 The character, string data Types Files

I/O Streams and Standard I/O Devices (cont d.)

EE 355 Lab 4 - Party Like A Char Star

String Class in C++ When the above code is compiled and executed, it produces result something as follows: cin and strings

System Design and Programming II

Chapter 3 - Notes Input/Output

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

13 4 Understanding Character Strings

String Objects: The string class library

The C++ Language. Arizona State University 1

ONE DIMENSIONAL ARRAYS

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Software Design & Programming I

Introduction to string

Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Computer Science & Engineering 150A Problem Solving Using Computers

CPE Summer 2015 Exam I (150 pts) June 18, 2015

C++ basics Getting started with, and Data Types.

Dodatak D Standardna string klasa

CSCE 110 PROGRAMMING FUNDAMENTALS

Object oriented programming C++

Week 3: File I/O and Formatting 3.7 Formatting Output

C mini reference. 5 Binary numbers 12

Objectives. In this chapter, you will:

Chapter 10. Arrays and Strings

Note 11/13/2014. They are like those i s, j s, and temp s that appear and disappear when the function starts and finishes...

C++ Input/Output Chapter 4 Topics

Built-in Functions for NTCAs.

by Pearson Education, Inc. All Rights Reserved. 2

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

CS150 Intro to CS I. Fall Fall 2017 CS150 - Intro to CS I 1

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Unit 14. Passing Arrays & C++ Strings

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

CSCI 6610: Review. Chapter 7: Numbers Chapter 8: Characters Chapter 11 Pointers

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

1 Pointer Concepts. 1.1 Pointer Examples

Assignment 5: MyString COP3330 Fall 2017

Chapter 8 - Characters and Strings

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Chapter 8 C Characters and Strings

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Definition Matching (10 Points)

Applied C and C++ Programming

C++ Input/Output: Streams

COMSW Introduction to Computer Programming in C

CS2141 Software Development using C/C++ C++ Basics

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

CSC 126 FINAL EXAMINATION FINAL Spring 2012 B. Name (last, First) Instructor. Total Possible. Received

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Absolute C++ Walter Savitch

Chapter 2: Basic Elements of C++

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

COP Programming Assignment #7

2. First Program Stuff

CS 115 Exam 3, Spring 2010

Chapter 8: Character & String. In this chapter, you ll learn about;

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Objectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will:

Transcription:

Chapter 8

In this chapter, you will learn about: An Array Type for Strings The Standard string Class Vectors

The C Language Representation of Strings (C-Strings) The C-String Variable: Array of Characters The Null Character '\0' used to Mark End of String in Array The '\0' is a Single Character Stored in One Indexed Array Variable

Lets Declare a C-String for 10 Characters: char s[11]; The 10 Characters are stored in Indexed variables: s[0], s[1],, s[9] The null character \0 is stored s[10] Example: s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9] s[10] K E N T S T A T E \0

Consider C-string variable: char s[11]; Then 10 or less Characters can be stored in C-String variable s: Example: s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9] s[10] C S 2 3 0 2 1 \0?? C-String Variable, s Stores 8 Characters

1. Initialize in Declaration Statement (with Size specified): char your_string[ 19] = To Be Or Not To Be ; [0] [17] [18] T o B e O r N o t T o B e \0 The null character is automatically added 2. Initialize in Declaration Statement (Omit size) char my_string[ ] = To Be ; [0] [4] T o B e \0 String length is 5 Variable has size one character longer than length of string

Consider initialization: Char our_string[ ] = { T, o,, B, e }; Is our_string a C-string variable?

Consider initialization: char our_string[ ] = { T, o,, B, e }; Is our_string a C-string variable? [0] [4] T o B e The array our_string does not contain a null character Not a C-string

Caution Do not to Destroy the null character when Manipulating Indexed Variables in a C-string Example: char our_string[10] = To Be ; int index = 0; while (our_string[index]!= '\0') { our_string[index] = 'X'; index++; } This code depends on finding the null character! The array no longer acts like a C-string when \0 is replaced

Illegal Assignment statement: our_string = To Be ; The assignment operator = does not work with C-String

Assignment using strcpy #include <cstring> // strcpy is defined in this library char my_string[ 6]; strcpy (my_string, "Hello"); // Places "Hello" followed by the null character in my_string strcpy does not check the declared length of the first argument, my_string strcpy may copy characters beyond the declared size of the array: char my_string[6]; strcpy (my_string, Hello World );

strncpy (another_string, a_string, n); Copies up to n characters from a_string to another_string #include <cstring> // strncpy is defined in this library char another_string[ 10]; strncpy (another_string, a_string, 9); // Copies up to 9 characters from a_string to another_string leaving one // space for \0

The = = operator does not work with C-strings Use function strcmp (i.e. String Compare) instead Example #include <cstring> //strcmp is defined in this library if (strcmp(c_string1, c_string2)) cout << "Strings are not the same."; else cout << "String are the same.";

strcmp compares the numeric codes (e.g., ASCII representation) of elements in the C-strings one character at a time strcmp returns: 0 if the two C-strings are the same Note 0 is interpreted as false Negative Value if the numeric code in the first parameter is less than that of the second Positive Value if the numeric code in the second parameter is less than that of the first Note Non-zero values (Positive/Negative) are interpreted as true

! " strlen strlen returns the number (Integer value) of characters in a string int x = strlen( a_string); strcat strcat concatenates two C-strings The second argument is added to the end of the first The result is placed in the first argument Example: char string_var[20] = Summer"; strcat(string_var, Holidays"); Now string_var contains SummerHolidays" Do you see a problem with strcat?

! " strncat is a safer version of strcat char rithm[11] = Rainny"; strncat(rithm, Day in Georgia", 4); Specifies a limit for the number of characters to append Now, rithm contains 11 characters plus the null terminator: Rainny Day\0 Refer to Pages 456 and 983 for more pre-defined functions

Recall, C-string variable is char array Hence if C-string variable is an array parameter Since functions can change array parameters: Include an additional int parameter for the declared size of the C-string variable The function will use the declared size to manipulate the C-string

# Use the insertion operator to output a C-string Example: char new_course[ ] = Requirements Engineering "; cout << new_course << " Wow." << endl;

Use the extraction operator >> to read characters into a C-string: Note: Whitespaces delineate data items Example: char a[80], b[80]; cout << "Enter input: " << endl; cin >> a >> b; cout << a << b << "End of Output"; a[0]a[1] b[0]b[1] D 0 b e Output could produce: Enter input: Do be do to you! DobeEnd of Output

$ Use member function: getline To read a line of input (including spaces) and store the characters into a C-string variable getline is a member of all input streams Syntax cin.getline(string_var, Max_Character +1); One line of input will be read from Input Stream Holds characters read Maximum characters read Reserved for \0

The following code is used to read an entire line including spaces into a single C-string variable char phrase[80]; cout << "Enter input:\n"; cin.getline(a, 80); cout << a <<! <<End Of Output\n"; Output Enter input To Be Or Not To Be To Be Or Not To Be! End Of Output User types

C-String File Input/Output Streams C-string input and output work the same way with file streams Replace cin with the name of an input-file stream in_stream >> c_string; in_stream.getline(c_string, 80); Replace cout with the name of an output-file stream out_stream << c_string;

C-string Number Conversion Recall 1234 is different from 1234 1234" is a sequence of characters (String) 1234 is a number When designing numeric input, it is useful to read data as a string of characters, edit the string then convert the string to a number If reading money input may or may not have dollar sign If reading percentages input may or may not have percent sign at the end

C-string Number Functions To read an integer as characters Read input as characters into a C-string, edit unwanted characters Use the predefined function atoi to convert the C-string to an integer value Example: #include <cstdlib> atoi("1234") returns the integer 1234 atoi("#123") returns 0 because # is not a digit Use pre-define functions to edit the C-string: isdigit( )

C-strings can be converted to type double using predefined function atof atof returns a value of type double Example: #include <cstdlib> atof("9.99") returns 9.99 atof("$9.99") returns 0.0 because the $ is not a digit

% Recall C-string: Array of Character terminated by \0 Programmer needs to track low-level storage details for string manipulation The string class allows: Programmer to treat strings as another Basic data type No need to worry about low-level details

% & To use the string class you need to insert the following lines: #include <string> using namespace std; Why?

% # Use the operator = to assign a value to a string Example: Assign a string object to another string object string s2, s4, s6; s2 = s4; Example: Assign a C- string to string object string s2, s4, s6; s6 = To Be Or Not To Be ; Typed cast to string Object

% ' Use the + operator to Concatenate string objects Example: string s2, s4, s6; s2 = s4 + s6; If the combined length of s4 and s6 exceeds the capacity of s2, more space will be allocated for s2

% Declaration initializes string variable to empty string Default Construct string phrase; Declarations initialize string variable to value equivalent to C-string ants without trailing \0 Using C-string argument: string noun( ants ) string noun = ants ;

% ' You can Concatenate string objects and C-strings: Example string phrase, adjective, noun; phrase = "I love" + adjective + " " + noun + "!"; How? Type conversion of C-string to string object Or Using overloading for operator +

% #' Use Insertion Operator << to output string objects Example string phrase; phrase = To Be Or Not To Be ; cout << phrase; To Be Or Not To Be Use the Extraction Operator >> to input value into string objects: Example string s1, s2; cin >> s1; cin >> s2; s1 The s2 Kent User types: The Kent State University Cannot use cin to read a blank character Blank character/whitespace is a delimiter for cin

% $ ( )% *+! Use cin.get to read a blank character into a char variable not string object char next_char; cin.get ( next_char); How do you read an entire line into a string variable? Use the getline non-member function: Syntax: getline(istream_object, String_Object);

% $ +! Example -1 Read entire line into string object string line; cout "Enter a line of input:\n"; getline(cin, line); cout << line << "END OF OUTPUT\n"; Reads until \n is encountered Example -1 Possible Output Enter some input: Spring is Here! Spring is Here!END OF OUTPUT User types

% $ +! Example -2 Read up to an end-of line marker into string object string line; cout "Enter some line input:\n"; getline(cin, line,? ); cout << line << "END OF OUTPUT\n"; Reads until? is encountered Example -1 Possible Output Enter some input: Summer? No Spring is Here! SummerEND OF OUTPUT User types The getline function stops reading at a character specified in the 3 rd Argument

% getline (cin, s1) Reads in a line of text into s1 returns a reference to its first argument (cin) Example: string s1, s2; getline(cin, s1) >> s2; Results in: cin >> s2;

% istream& getline(istream& ins, string& str_var); istream& getline(istream& ins, string& str_var, char delimiter);

%,,-. Recall cin >> n: Skips leading blank characters Reads non-blank characters Stops reading when a blank character is encountered Consider code segment: int n; string line; cin >> n; getline (cin, line); Suppose input: 42 Computer Science What is the output of code? Can you explain why? n 42 line Empty

% / ignore is a member of the istream class ignore can be used to read and discard all the characters, including '\n' that remain in a line Ignore takes two arguments First argument: the maximum number of characters to discard Second argument: the character that stops reading and discarding Example: cin.ignore(1000, '\n'); Discards rest of line up to \n If \n not found, discards the leading 1000 characters

% Can perform all C-string Operations and more using class strings Accessing a Character in string Object: string my_name = John Doe ; my_name[4] = - ; cout << my_name; John-Doe Caution: my_name[i] does not validate the index i

% % Use the class member function, length, to find the number of characters in a string Length of String: string my_name = John Doe ; int = size; size = my_name.length( ); cout << size; 8

% % Safer to use Member Function at to index a string object instead of the [i] indexing notation The at checks for illegal index values: string str( Mary ); cout << str[6] << endl; Illegal operation Why? May not generate any error message string str( Mary ); cout << str.at(6) << endl; Illegal operation gives error message Terminates the program execution str[3] = k ; str.at(3) = k ;

% # Can compare two string objects using the following operators: ==, <, >, <=, >= Remember strcmp ( ) for c-string?? See Page 479 for other string class functions

% -0#' Recall, automatic conversion from C-string to string: char c_phrase[ ] = To Be Or Not To Be"; string s_phrase = c_phrase; You cannot convert strings to C-strings char c_phrase [ ] = To Be Or Not To Be ; string s_phrase = Spring Time ; c_phrase = s_phrase; strcpy(c_phrase, s_phrase); Illegal Statements!

% % #' To obtain a C-string corresponding to string object: Use the Member function c_str( ); char c_phrase[5 ]; string s_phrase = Kent"; strcpy (c_phrase, s_phrase.c_str( ));

( Vectors are Similar to Arrays Base Type (e.g., int, double, char, float) Store elements of the same type But, unlike Arrays they can Grow and Shrink in Length while the Program Runs Vector size is not fixed Standard Template Library (STL) So how do we declare a vector? Standard Data Structures to organize and manipulate data items Container Classes: Vectors, Stack, Queues, lists Generic Algorithms: Template Functions for Searching, Sorting,..

To Declare an Empty Vector (v) with a Base type int: vector <int> v; To Declare an Empty Vector (s) with a Base type string: vector <string> s; Base Type Template Class

How do you access elements of a vector? Use Indexing [ ], similar to arrays: Example: Assume vector (v) is already initialized Then to change the i th element: v[ i ] = 42; cout << The result is << v[ i ]; Note, use indexing to: Read a vector element that already has a value Change a Vector element that already has a value Cannot use indexing to initialize a vector

To add an element to a vector position for the first time Use Member function: push_back Example: vector<double> sample; sample.push_back(2.0); sample.push_back(4.2); sample.push_back(6.4); // Adds 2.0 in position 0 // Adds 4.2 in position 1 // Adds 6.4 in position 2 push_back adds an element in the next available position

To determine number of elements in a vector (Length of vector) Use Member function: size Example Vector Initialization: vector<double> sample; sample.push_back(2.0); sample.push_back(4.2); sample.push_back(6.4); for (unsigned int i= 0; i < sample.size( ); i++) cout << sample[i] << endl; // Adds 2.0 in position 0 // Adds 4.2 in position 1 // Adds 6.4 in position 2 Member Function sample.size returns an unsigned integer

Construct to Initialize Vector to 0 values: Example: vector <int> v(10) // Initializes v[0], v[1],., v[9] to zero After the initialization, now, we can: assign values to elements v[0], v[1],, v[9] Use Indexing [ ] But use push_back to assign elements v[10], v[11],

To use the vector class Include the following two lines: #include <vector> using namespace std;

Using Square brackets beyond the Vector Size Consider v[i] = n; where i > v.isize( ) This will not generate an error message, but your code will not work properly

+ A vector's capacity refers to the number of elements allocated in memory for storing the vector Accessible using the capacity( ) member function A vector s Size is the number of elements initialized When a vector runs out of space, the capacity is automatically increased A common scheme is to double the size of a vector More efficient than allocating smaller chunks of memory

To Increase the Capacity of a Vector: Use member function reserve( ) Example: v.reserve(32); // at least 32 elements v.reserve(v.size( ) + 10); // at least 10 more To shrink a vector: Use member function resize( ) Example: v.resize(24); //elements beyond 24 are lost