Unit 2: The string class

Similar documents
Copyright 2003 Pearson Education, Inc. Slide 1

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

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

BITG 1113: Array (Part 2) LECTURE 9

Introduction to string

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

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

Intermediate Programming, Spring 2017*

1 Pointer Concepts. 1.1 Pointer Examples

EE 355 Lab 4 - Party Like A Char Star

Computers Programming Course 11. Iulian Năstac

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

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.

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

C-String Library Functions

Lecture 3 The character, string data Types Files

Chapter 10 Characters, Strings, and the string class

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

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

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

Chapter 8 - Characters and Strings

Structured programming

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

CS 103 Lab 6 - Party Like A Char Star

CS242 COMPUTER PROGRAMMING

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

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

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

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

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

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

String Objects: The string class library

LECTURE 15. String I/O and cstring library

CSCE 110 PROGRAMMING FUNDAMENTALS

CHAPTER 3 Expressions, Functions, Output

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

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

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

Engineering Problem Solving with C++, Etter

C: How to Program. Week /May/28

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

System Design and Programming II

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

CS 103 Lab - Party Like A Char Star

Object Oriented Programming COP3330 / CGS5409

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

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 (!

Definition Matching (10 Points)

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

C Characters and Strings

Topic 3. Big C++ by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

CS107 Spring 2019, Lecture 4 C Strings

Study Guide for Test 2

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

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

by Pearson Education, Inc. All Rights Reserved.

Objectives. In this chapter, you will:

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

CS107, Lecture 4 C Strings

Coursework 2: Basic Programming

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

Arrays in C++ Instructor: Andy Abreu

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

Chapter 8 C Characters and Strings

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

1. In C++, reserved words are the same as predefined identifiers. a. True

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Dodatak D Standardna string klasa

Exercise 1.1 Hello world

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

CCE1111 Programming for Engineers [C Programming Language]

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:

C++ Lab 02 - Command Line Arguments and Strings

UNIT- 3 Introduction to C++

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:

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Create a Program in C (Last Class)

C mini reference. 5 Binary numbers 12

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Strings. Daily Puzzle

Built-in Functions for NTCAs.

ONE DIMENSIONAL ARRAYS

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

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

C Language: Review. INFO High Performance Scientific Computing. 26 septembre 2017

Chapter 9 Strings. With this array declaration: char s[10];

The C++ Language. Arizona State University 1

Computer Programming: Skills & Concepts (CP) Strings

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

CS11 Advanced C++ Lecture 2 Fall

Chapter 2: Basic Elements of C++

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

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Transcription:

: class Programming 2 2015-2016

Index 1 characters in C 2 Input / output 3 Conversion between arrays of characters and strings 4 Comparison with arrays of characters 5

characters in C characters in C have a constant (fixed) length: char cad[10]; It is also possible to declare them with a dynamic length in different ways: int tamcad; cin >> tamcad; char cad[tamcad]; // Not recommended by standard char *cad = (char *)malloc(tamcad*sizeof(char)); // C char *cad = new char[tamcad]; // C++ However, once declared they cannot change their size.

with C character arrays from C++ cout : like other simple variables (int, float,... ) Beware: the character array must end with \0 cin : almost like other variables cin ignore blanks before the character array... It stops reading when the first space, tab or \n is read afterwards. Problem: what happens if the character array contains blanks? It doesn t limit the number of characters to be read. BIG PROBLEM: what happens if the characters don t fit into the array?

getline Using getline, arrays can be read with blanks and their size can be controlled. cin.getline(cadena,tam) It reads as maximum TAM-1 characters or until the end of the line The character \n at the end of the line is read but not stored into the array. It adds the character \0 at the end of the contents that were read (that s why it only reads TAM-1 characters)... but if the user introduces more characters than the maximum, they remain in the buffer and the next reading fails.

Problems mixing» with getline int num; cout << "Num= "; cin >> num; char cadena[1000]; cout << "Write something: " ; cin.getline(cadena,1000); cout << "I read: " << cadena << endl; Num= 10 Write something: I read: Why? Using >>, 10 is read, but it stops reading at the first character which is not a number \n getline finds a \n in the buffer, therefore an empty array of characters is read. Solution: cin >> num; cin.get(); // Reads \n

Functions in string.h (1/2) strlen returns the length of an array of characters. char cad[] = "bye!"; cout << strlen(cad) << endl; // Prints 4 strcmp compares two arrays in lexicographical order, returning a negative value if a < b, zero if a == b, or positive if a > b. char cad[] = "adios"; char otra[] = "adeu"; cout << strcmp(cad,otra) << strcmp(otra,cad) << strcmp(cad,cad) << endl; // Prints 1-1 0 strcpy copies an array into another (beware, segmentation fault if it does not fit) char cad[10]; strcpy(cad,"hola"); // fits, there are 4 + \0 = 5 chars

Functions in string.h (2/2) The functions strncmp, strncpy compare or copy only the first n characters. Example: char cad[tcad]; strncpy(cad,"hola, mundo",4); // It only copies "hola" cad[4] = \0 ; // It does not automatically copy \0 To convert an array of characters into an integer or a float, you can use atoi, or atof. #include <cstdlib> // Important! char cad[]="100"; int n=atoi(cad); // n is 100 char cad2[]="10.5"; float f=atof(cad2); // f is 10.5

Strings in C++: class can be used in C++ (although arrays of characters can also be used) Passing strings as function parameters (by value or reference) is similar to any simple type (int, float,... ), length is variable (there is no maximum limit), and it can grow It doesn t end with \0

Constant: const string cadena="hola"; Variable: string cadena; with initialization: string cadena = "hola";

with strings cout : like simple types (int, float,... ) cin : almost like the arrays of characters Blanks before the string are ignored, and reading stops when the first blank after the data is found. String containing blanks can also be read: getline(cin,cadena) (warning, the syntax is different to that of arrays of characters) The number of characters to be read is not constrained Warning: Calling >> and afterwards getline produces the same problems seen with arrays of characters You can read until a given character using: getline(cin,cadena,, )

string methods (1/2) A string is a class, therefore methods are called using a dot after the variable name. Example: unsigned int tam=s.length(); // s is a string String length: unsigned int length(); Substring search: unsigned int find (const string str, unsigned int pos=0); // If not found, it returns the string::npos constant Substring replacement: string& replace (unsigned int pos, unsigned int tam, const string str); Remove a substring string& erase (unsigned int pos=0, unsigned int tam=npos);

string methods (2/2) string a="hay una taza en esta cocina con tazas"; string b="taza"; // Length of a unsigned int tam = a.length(); // Searching for the first word taza unsigned int encontrado=a.find(b); if (encontrado!=string::npos) cout << "primera taza en: " << encontrado << endl; else cout << "palabra taza no encontrada"; // Searching for the second word taza encontrado=a.find("taza",encontrado+b.length()); if (encontrado!=string::npos) cout << "segunda taza en: " << encontrado << endl; else cout << "palabra taza no encontrada"; // The first taza is replaced by botella a.replace(a.find(b),b.length(),"botella"); cout << a << endl;

string operations Comparisons: ==,!=, >, <, >= and <= String assignment: using operator =, like with simple types. String concatenation: using operator + s1 = "hola" ; s2 = "mundo"; s = s1 + ", " + s2; cout << s << endl ; // prints hola, mundo Components can be accessed like in arrays of characteres: only if the string contains something there. s = "hola" ; car = s[3]; s[0] = H ; cout << s << ":" << car << endl ; // prints Hola:a // Loop example for (unsigned int i=0; i<s.length(); i++) s[i]= f ;

Conversion between arrays of characters and strings array of characters to string: using the assignment operator (=) char cad[] = "hola"; string s ; s = cad ; s = s + ", mundo"; string to array of characters : using c_str char cad[tcad]; string s = "mundo"; // Warning: cad must be long enough strcpy(cad, s.c_str());

Conversion between string and integer Integer to string #include <sstream> int n=100; stringstream ss; ss << n; // More data can be concatenated, e.g.: // ss << "The number is: " << n << endl; string number=ss.str(); string to integer string number="100"; int n=atoi(number.c_str());

Tokenize strings You can extract fields from a string using the class stringstream. For example: #include <sstream> int main() { stringstream ss("hola mundo cruel 1 32 2"); string s; while (ss>>s) { cout << "s: " << s << endl; } }

Comparison between arrays of characters and strings arrays of characters string char cad[tam]; string s; char cad[]="hola"; string s="hola"; strlen(cad) s.length() cin.getline(cad,tam); getline(cin,s); if (!strcmp(c1,c2)){..} if (s1 == s2){..} strcpy(c1,c2); s1 = s2; strcat(c1,c2); s1 = s1 + s2; strcpy(cad,s.c_str()); s = cad; They end with \0 They DON T end with \0 Fixed length Variable length (it can grow) Variable used size Used size = reserved size They can be used in binary files They CAN T be used in binary files

(1/4) Exercise 1 Design a function called SubCadena to extract a substring of length n, starting from the position p of other string. Both the argument and the return variable must be strings. SubCadena("hoooola", 2, 5) "la" Exercise 2 Design a function called BorraCaracterDeCadena. Given a string and a character, it must delete all the occurrences of the character in the string. "hola, mundo" o "hla, mund"

(2/4) Exercise 3 Design a function BuscarSubCadena to find the first occurrence of the substring a into the string b, returning its position, or 1 if it is not found. Variables a and b must be strings. BuscarSubCadena("oool", "hoooola") 2 Extensions: 1 Extend the function to allow another parameter, the occurrence number (being 1, it would be like the original function, searching for the first occurrence) 2 Implement a similar function returning the total number of occurrences of a in b.

(3/4) Exercise 4 Design a function called Codifica for encrypting a string by summing a constant value c to the ASCII code of each character. It must be considered that the result should be a letter. For instance, if n = 3, a is coded as d, b as e,..., x as a, y as b, and z as c. The function must allow uppercase and lowercase letters, and the non-letter characters shouldn t be encrypted. Codifica("hola, mundo", 3) "krod, pxqgr"

(4/4) Exercise 5 Design a function EsPalindromo to return true if the string passed as parameter is palindromic. EsPalindromo("hola,aloh") true EsPalindromo("hola, aloh") false Exercise 6 Design a function called CreaPalindromo for adding to a given string the same one but reversed, in such a way that the output string will be palindromic. "hola, mundo" "hola, mundoodnum,aloh" This can be done in two ways: string CreaPalindromo(string); void CreaPalindromo(string &);