CS106X Handout 04 Winter 2018 January 8 th, 2018 C++ Strings

Similar documents
CS106X Handout 04 Autumn 2009 September 25 th, 2009 C++ Strings

CS106B Handout #5 Winter January 9, 04

A couple of decent C++ web resources you might want to bookmark:

String Objects: The string class library

Engineering Problem Solving with C++, Etter

Assignment #1 Simple C++

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:

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Programming Abstractions

Lecture 3 The character, string data Types Files

Unit 14. Passing Arrays & C++ Strings

STRINGS AND STRINGBUILDERS. Spring 2019

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

Chapter 10 Characters, Strings, and the string class


Working with Strings. Lecture 2. Hartmut Kaiser. hkaiser/spring_2015/csc1254.html

CSCE 110 PROGRAMMING FUNDAMENTALS

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 8 - Notes User-Defined Simple Data Types, Namespaces, and the string Type

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

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

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

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

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

Strings and Stream I/O

Object Oriented Programming COP3330 / CGS5409

Chapter 3 - Notes Input/Output

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

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

LECTURE 15. String I/O and cstring library

CS201- Introduction to Programming Current Quizzes

EECS402 Lecture 08. Intro To The Standard string Class. Some string Functionality

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Definition Matching (10 Points)

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

Computer Programming

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

Programming Abstractions

Separate Compilation Model

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

The C++ Language. Arizona State University 1

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

Simple File I/O.

Preprocessor Directives

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

COP 3014: Fall Final Study Guide. December 5, You will have an opportunity to earn 15 extra credit points.

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

Assignment 5: MyString COP3330 Fall 2017

Integer Data Types. Data Type. Data Types. int, short int, long int

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:

CSCE121: Introduction to Program Design and Concepts Practice Questions for Midterm 1

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

CMPT 125: Lecture 3 Data and Expressions

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

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015

Objectives. In this chapter, you will:

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

Honors Computer Science C++ Mr. Clausen Program 3A, 3B, 3C

Computer Programming

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #33 Pointer Arithmetic

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

PAIRS AND LISTS 6. GEORGE WANG Department of Electrical Engineering and Computer Sciences University of California, Berkeley

Lab: Supplying Inputs to Programs

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

std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin

CHAPTER 3 Expressions, Functions, Output

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Scheme: Strings Scheme: I/O

To practice overall problem-solving skills, as well as general design of a program

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

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

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

STUDENT LESSON A10 The String Class

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

C++ Programming: From Problem Analysis to Program Design, Third Edition

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

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

Variables. Data Types.

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

COMP322 - Introduction to C++

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Unit E Step-by-Step: Programming with Python

LESSON 4. The DATA TYPE char

COMP322 - Introduction to C++

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

Fundamentals of Python: First Programs. Chapter 4: Strings and Text Files

C++_ MARKS 40 MIN

Cpt S 122 Data Structures. Introduction to C++ Part II

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Transcription:

CS106X Handout 04 Winter 2018 January 8 th, 2018 C++ Strings C++ Strings Original handout written by Neal Kanodia and Steve Jacobson. One of the most useful data types supplied in the C++ libraries is the string. A string is a variable that stores a sequence of letters or other characters, such as "Hello" or "May 10th is my birthday!". Just like the other data types, to create a string we first declare it, then we can store a value in it. string teststring; teststring = "This is a string."; We can combine these two statements into one line: string teststring = "This is a string."; Often, we use strings as output, and cout works exactly like one would expect: cout << teststring << endl; will print the same result as cout << "This is a string." << endl; In order to use the string data type, the C++ string header <string> must be included at the top of the program. Also, you ll need to include to make the short name string visible instead of requiring the cumbersome std::string. (As a side note, std is a C++ namespace for many pieces of functionality that are provided in standard C++ libraries. For the purposes of this class, you won't need to otherwise know about namespaces.) That means you need the following #include in your program in order to use the string type. Basic Operations Let s go into specifics about the string manipulations you ll be doing the most. Counting the number of characters in a string. The length method returns the number of characters in a string, including spaces and punctuation. Like many of the string operations, length is a member function, and we invoke member functions using dot notation. The string that is the receiver is to the left of the dot, the member function we are invoking is to the right, (e.g. str.length()). In such an expression, we are requesting the length from the variable str.

2 string small, large; small = "I am short"; large = "I, friend, am a long and elaborate string indeed"; cout << "The short string is " << small.length() << " characters." << endl; cout << The long string is " << large.length() << " characters." << endl; The short string is 10 characters. The long string is 48 characters. Accessing individual characters. Using square brackets, you can access individual characters within a string as if it s a char array. Positions within a string str are numbered from 0 through str.length() - 1. You can read and write to characters within a string using []. string test; test = "I am Q the omnipot3nt"; char ch = test[5]; test[18] = 'e'; // ch is 'Q' // we correct misspelling of omnipotent cout << test << endl; cout << "ch = " << ch << endl; I am Q the omnipotent ch = Q Be careful not to access positions outside the bounds of the string. The square bracket operator is not range-checked and thus reading from or writing to an out-of-bounds index tends to produce difficult-to-track-down errors. There is an alternate member function

at(int index) that retrieves the character at a position with the benefit of built-in range-checking, but it s used much less often. Passing, returning, assigning strings. C++ strings are designed to behave like ordinary primitive types with regard to assignment. Assigning one string to another makes a deep copy of the character sequence. string str1 = "hello"; string str2 = str1; // makes a new copy str1[0] = 'y'; // changes str1, but not str2 Passing and returning strings from functions clones the string. If you change a string parameter within a function, changes are not seen in the calling function unless you have specifically passed the string by reference (e.g. using that & trick we learned about in the Queen Safety example.) Comparing two strings. You can compare two strings for equality using the == and!= operators. Suppose you ask the user for his or her name. If the user is Julie, the program prints a warm welcome. If the user is not Neal, the program prints the normal message. Finally if the user is Neal, it prints a less enthusiastic response. #include "simpio.h" string myname = "Neal"; while (true) { cout << "Enter your name (or 'quit' to exit): "; string username = getline(); if (username == "Julie") { cout << "Hi, Julie! Welcome back!" << endl; else if (username == "quit") { // user is sick of entering names, so let's quit cout << endl; break; else if (username!= myname) { // user did not enter quit, Julie, or Neal cout << "Hello, " << username << endl; else { cout << "Oh, it s you, " << myname << endl; 3

4 Enter your name (or 'quit' to exit): Neal Oh, it's you, Neal Enter your name (or 'quit' to exit): Julie Hi, Julie! Welcome back! Enter your name (or 'quit' to exit): Leland Hello, Leland Enter your name (or 'quit' to exit): quit You can use <, <=, >, and >= to compare strings as well. These operators compare strings lexicographically, character by character and are case-sensitive. The following comparisons all evaluate to true: "A" < "B", "App" < "Apple", "help" > "hello", "Apple" < "apple". The last one might be a bit confusing, but the ASCII value for 'A' is 65, and comes before 'a', whose ASCII value is 97. So "Apple" comes before "apple" (or, for that matter, any other word that starts with a lower-case letter). Appending to a string: C++ strings are wondrous things. Suppose you have two strings, s1 and s2 and you want to create a new string of their concatenation. Conveniently, you can just write s1 + s2, and you ll get the result you d expect. Similarly, if you want to append to the end of string, you can use the += operator. You can append either another string or a single character to the end of a string. string firstname = "Leland"; string lastname = " Stanford"; string fullname = firstname + lastname; // concat the two strings fullname += ", Jr"; // append another string fullname += '.'; // append a single char cout << firstname << lastname << endl; cout << fullname << endl; Leland Stanford Leland Stanford, Jr.

More (Less Used) Operations The string class has many more operations; we ll show just a few of the more useful ones below. Searching within a string. The string member function find is used to search within a string for a particular string or character. A sample usage such as str.find(key) searches the receiver string str for the key. The parameter key can either be a string or a character. (We say the find member function is overloaded to allow more than one usage). The return value is either the starting position where the key was found or the constant string::npos which indicates the key was not found. Occasionally, you ll want to control what part of the string is searched, such as to find a second occurrence past the first. There is an optional second integer argument to find which allows you to specify the starting position; when this argument is not given, 0 is assumed. Thus, str.find(key, n) starts at position n within str and will attempt to find key from that point on. The following code should make this slightly clearer: string sentence = "Yes, we went to Gates after we left the dorm."; int firstwe = sentence.find("we"); // finds the first "we" int secondwe = sentence.find("we", firstwe + 1); // finds "we" in "went" int thirdwe = sentence.find("we", secondwe + 1); // finds the last "we" int gpos = sentence.find('g'); int zpos = sentence.find('z'); // returns string::npos cout << "First we: " << firstwe << endl; cout << "Second we: " << secondwe << endl; cout << "Third we: " << thirdwe << endl; cout << "Is G there? "; cout << (gpos!= string::npos? "Yes!" : "No!") << endl; cout << "Is Z there? "; cout << (wpos!= string::npos? "Yes!" : "No!") << endl; First we: 5 Second we: 8 Third we: 28 Is G there? Yes! Is Z there? No! Extracting substrings. Sometimes you would like to create new strings by extracting portions of a larger one. The substr member function creates substrings from pieces of 5

the receiver string. You specify the starting position and the number of characters. For example, str.substr(start, length) returns a new string consisting of the characters from str starting at the position start and continuing for length characters. Invoking this member function does not change the receiver string, as it makes a new string with a copy of the characters specified. string oldsentence; oldsentence = "The quick brown fox jumped WAY over the lazy dog"; int len = oldsentence.length(); cout << "Original sentence: " << oldsentence << endl; int found = oldsentence.find("way "); string newsentence = oldsentence.substr(0, found); cout << "Modified sentence: " << newsentence << endl; newsentence += oldsentence.substr(found + 4); cout << "Completed sentence: " << newsentence << endl; Original sentence: The quick brown fox jumped WAY over the lazy dog Modified sentence: The quick brown fox jumped Completed sentence: The quick brown fox jumped over the lazy dog 6 There are a couple of special cases for substr(start, length). If start is negative, it will cause a run-time error. If start is past the end of the string, it will return an empty string (e.g., ""). If length is longer than the number of characters from the start position to the end of the string, it truncates to the end of the string. If length is negative, then the behavior is undefined, so make sure that length is always non-negative. If you leave off the second argument, the number of characters from the starting position to the end of the receiver string is assumed.

Modifying a string by inserting and replacing. Finally, let s cover two other useful member functions that modify the receiver string. The first, str1.insert(start, str2), inserts str2 at position start within str1, shifting the remaining characters of str1 over. The second, str1.replace(start, length, str2), removes from str1 a total of length characters starting at the position start, replacing them with a copy of str2. It is important to note that these member functions do modify the receiver string. string sentence = "CS106X sucks."; cout << sentence << endl; // Insert "kind of" at position 8 in sentence sentence.insert(7, "kind of "); cout << sentence << endl; 7 // Replace the 10 characters "kind of su" // with the string "ro" in sentence sentence.replace(7, 10, "ro"); cout << sentence << endl; CS106X sucks. CS106X kind of sucks. CS106X rocks. Obtaining a C-style char * from a string Remember, a C++ string is not the same thing as a C-style string (which is merely a char * pointer to a sequence of characters terminated by a null character '\0'). Although old-style C char * strings and C++ strings can co-exist in a program, almost all our use will be of C++ strings, since they have a much richer set of operations and are less error-prone to work with. I say "almost always" because in a few unavoidable situations, we are forced to use old-style C strings, most notably when working with file streams. We can convert a C++ string to the old-style representation using the.c_str() member function. One use we will see of this is to get a char * to pass to the iostream::open function.

8 #include <fstream> ifstream fs; string filename = "courseinfo.txt"; string s; // open function requires a C-style string, must convert! fs.open(filename.c_str()); if (fs.fail()) return -1; // could not open the file! // process the file fs.close(); The CS106 Library: strlib.h In addition to the standard library support for strings, there are a few extensions that the CS106 libraries provide. To use these functions, the strlib.h library must be #included. integertostring, realtostring, stringtointeger, stringtoreal: Often your programs will need to convert a string to a number or vice versa. These functions do just that, with the 'integer' functions operating on int and the 'real' functions on double. #include "genlib.h" #include "strlib.h" string str1 = "5.6"; double num = stringtoreal(str1); string str2 = integertostring(45); cout << "The original string is " << str1 << "." << endl; cout << "The number is " << num << "." << endl; cout << "The new string is " << str2 << "." << endl;

9 The original string is 5.6. The number is 5.6 The new string is 45. Any integer or real can be safely converted to a string. However, when converting in the other direction, if you pass an improperly formatted string to convert to an integer or real, an error is raised by the conversion functions. topuppercase, tolowercase: These functions take a string, and return a new string with all letters in lower or upper case respectively. These can be used to change two strings to a uniform case before comparing to allow a case-insensitive comparison. #include "genlib.h" #include "strlib.h" string applefruit = "apples"; string orangefruit = "ORANGES"; cout << "Do " << applefruit << " come before " << orangefruit << "? "; cout << (applefruit < orangefruit? "Yes!" : "Nope...") << endl; string lowerorangefruit = tolowercase(orangefruit); cout << "Do " << applefruit << " come before " << lowerorangefruit << "? "; cout << (applefruit < lowerorangefruit? "Yes!" : "Nope...") << endl; Do apples come before ORANGES? Nope... Do apples come before oranges? Yes! There are a few other functions within the strlib library (equalsignorecase, startswith, endswith, and trim) as well.