CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Similar documents
Engineering Problem Solving with C++, Etter

Applied C and C++ Programming

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

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

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

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation

Computers Programming Course 11. Iulian Năstac

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

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

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

String Objects: The string class library

LECTURE 15. String I/O and cstring library

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

8. Characters, Strings and Files

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

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

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

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

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

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

Object Oriented Programming COP3330 / CGS5409

C-String Library Functions

ONE DIMENSIONAL ARRAYS

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Programming: Skills & Concepts (CP) Strings

Procedural Programming

ARRAYS(II Unit Part II)

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


C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

Chapter 10 Characters, Strings, and the string class

CS106L Handout #05 Fall 2007 October 3, C Strings

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

System Design and Programming II

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

CSCI 2212: Intermediate Programming / C Review, Chapters 10 and 11

1 Pointer Concepts. 1.1 Pointer Examples

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

Pointers, Arrays, and Strings. CS449 Spring 2016

Copyright 2003 Pearson Education, Inc. Slide 1

ECE551 Midterm Version 1

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

C mini reference. 5 Binary numbers 12

Procedural Programming & Fundamentals of Programming

Introduction to string

by Pearson Education, Inc. All Rights Reserved.

Principles of C and Memory Management

Characters and Strings

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

Chapter 8 Character Arrays and Strings

Week 5. Muhao Chen.

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.

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

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

Arrays, Strings, & Pointers

Programming for Engineers Arrays

Array Initialization

For example, let s say we define an array of char of size six:

Chapter 8 - Characters and Strings

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

13 4 Understanding Character Strings

C: How to Program. Week /May/28

Assignment 5: MyString COP3330 Fall 2017

CS 31 Discussion: Week 6. Taylor Caulfield

Intermediate Programming / C and C++ CSCI 6610

ECE551 Midterm Version 2

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

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

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

Intermediate Programming, Spring 2017*

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture7 Strings and Characters

Objectives. In this chapter, you will:

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

Characters, Character Strings, and string-manipulation functions in C

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

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

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Chapter 5. Section 5.1 Introduction to Strings. CS 50 Hathairat Rattanasook

C Programming. Unit 9. Manipulating Strings File Processing.

Intermediate Programming, Spring 2017*

ECE551 Midterm Version 1

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

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

BITG 1113: Array (Part 2) LECTURE 9

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

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

Lecture 3 The character, string data Types Files

Structured Types. 8. Arrays. collection of components whose organization is characterized by method used to access individual components.

CS107, Lecture 4 C Strings

C-LANGUAGE CURRICULAM

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

Computers Programming Course 10. Iulian Năstac

String constants. /* Demo: string constant */ #include <stdio.h> int main() {

Create a Program in C (Last Class)

Student Number: Instructor: Reid Section: L5101 (6:10-7:00pm)

Transcription:

... 1/26 CSCI 6610: Intermediate Programming / C Chapter 12 Alice E. Fischer February 10, 2016

... 2/26 Outline The C String Library String Processing in C Compare and Search in C C++ String Functions

... 3/26 What is a Literal String (review) Pictures of Examples

... 4/26 What is a string? The word string applies to objects of three different types in C: A literal string is zero or more characters enclosed in quotes. This kind of string has type const char*. A string is a null terminated array of characters. This kind of string has type char[]. Or a pointer to a char that is part of a null-terminated array of chars. This kind of string has type char*. The C compiler treats the last two types the same way in most situations.

... 5/26 About Literal. Literal strings are defined by writing them in your code. They are not variables and cannot be modified they are immutable. The compiler assigns read-only storage for literal strings and makes them available for you. You can output these strings or point at them.

... 6/26 About String Variables. If a string is stored in an array, it might or might not fill up the array. The \0 character marks the end of the string. After that, the contents of the array are garbage. You can modify the contents of the array by using assignment and/or the string functions. When scanf() inputs a string, it will ALWAYS end in \0. However, if the string is longer than the array that stores it, it will overwrite the value of some other variable. This is called walking on memory.

... 7/26 Pictures of. not a string H e l l o L e e compatible with string H e l l o L i \0 cstring, uninitialized immutable cstring "this is a const string" cstring H e l l o \0 two cstrings H e l l o \0

... 8/26 An Array of Arrays of strings are useful in many application. This data structure (often called a ragged array) has two parts: A backbone: an array of pointers. Several attachments of type char* or cstring, possibly const. words "one" "two" words "three" Conceptual view o n e \0 t w o \0 t h r e e \0 Physical view This is a 2-dimensional data structure: you can subscript the backbone, then you can subscript the strings attached to it.

... 9/26 How do you store a string in C? A string has two parts: a pointer and an array of characters. Memory must be declared or created dynamically for both. To declare a cstring variable (the pointer part) use type char* or use type cstring from the tools library. To declare the array part, create an array of chars that is long enough. This array will hold up to 9 chars and a null terminator: char ary[10]; We declare an array to be 1 longer than the longest possible contents because there must be space at the end of the data for a null terminator character, \0 Remember: a string can occupy many bytes of storage, and a pointer is just 4 bytes. So a char* cannot store a string.

... 10/26 How do you declare and create a string in C? You can declare an array to store a string WITHOUT initialization, like ary above. For this kind of declaration, you must give the maximum string length +1 in the square brackets. You can initialize a string in the declaration char greeting[] = "Hello"; You can also give BOTH the array length AND an initializer char name[16] = "A. Fischer"; When you choose the array length, consider the longest thing you intend to store in it. That is often longer than the initial value for the string.

... 11/26 How do you use a string in C? A cstring variable can point at one literal string, then later, be changed to point at another. It can point at either the beginning or the middle of a character array or literal string. To print a string, use printf( "%s", mystringname ); To input a string that does not have internal spaces, use scanf( "%ns", myarrayname ); The number n is the length-1 of the array you will be reading the string into. Inputting a string with internal spaces is more complex and will be handled later.

... 12/26 Input that Includes Whitespace in C Reading a string with embedded whitespace is more complex than reading one word in both C and C++. Suppose name is an array of 10 chars; read everything up to the next newline: scanf( "%9[^\n]", name ); Read everything up to the next delimiter, which is a comma here: scanf( "%9[^,]", name ); The delimiter, a newline or something else, is left in the input stream and will be read in by the next call on scanf(). To remove it from the stream and discard it on this read, add it to the format like this: scanf( "%9[^,],", name );

... 13/26 C Examples char* fname = "Alice"; // Point at string literal. char letters[20] = "Waltz"; char* lname = letters; // Point at letters[0]. char* fun = &fname[2]; // Point at fname[2]. printf("my name was %s %c. %s\n", fname, E, lname); lname = "Fischer"; printf("now my name is %s %c. %s ", fname, E,lname); printf("\ni like to skate on %s.\n", fun); Output: My name was Alice E. Waltz Now my name is Alice E. Fischer I like to skate on ice.

... 14/26 What is a string in C++? A C++ string is more complex than a C string and easier to use. It is an object with multiple parts, including an array for data, a counter for the number of data items in the array, and the current allocation size of the array. A C++ string can hold as much data as you put into it. When it gets full, it grows automatically by reallocating the data space. No memory management is necessary. A string manages its own memory. If you have a C++ string, you can extract the C string from it by calling c_str( mystring ); The type string is defined by STL (the Standard Template Library) and is derived from the STL type vector.

... 15/26 How do you declare a string in C++? Simple: string st; string st1( "Mary" ); string st2( st1 ); string st3 = "Jake" declares an empty string. declares and initializes a string Makes a copy of st1. Copy the literal into st3.... and there are other ways to construct strings that are less often needed.

... 16/26 How do you use a string in C++? You can input into a string variable: cin >> st; This will read one word (not a char, not a line) into the string. To input a string that has internal spaces, use getline(). getline( instr, mystring ); // Read to \n getline( instr, mystring, X ); // Read to 1st X. To print any string, use cout << mystring ; A parameter can be type string. In that case, the argument should also be a string, and the argument value is copied into the parameter variable.

... 17/26 A Few C++ String Functions String output is easy does not depend on the contents of the string. Suppose we have two C++ strings names str1 and str2: Use == to compare two strings for equality. if (str1 == str2) cout <<"This is easy." <<endl; Use == to compare a string to a literal. if (str2 == "Ann") cout <<"Also easy."; Extract the C-string from the C++ string: char* cstr = str2.c_str(); Find the length of a string: int len = str1.size(); Search a string for a character: int idx = str1.find_first_of("x")

... 18/26 C++ Examples string name ("Alice"); const char* lname = "Waltz"; string fun = name.substr(2, 3); // Point at the W // Get a substring. cout <<"My name was " <<name <<" E. " <<lname <<endl; lname = "Fischer"; cout <<"My name was " <<name <<" E. " <<lname <<endl; cout <<"I like to skate on " <<fun <<endl; Output: My name was Alice E. Waltz Now my name is Alice E. Fischer I like to skate on ice.

... 19/26 The C String Library The C String Library Basic String Operations Copying a String String Comparisons Searching a String An Array of A 2-D array of chars

... 20/26 The C String Library String Processing in C C String Operations char word[10] = "Hi" char* st = word; There are two ways to change a string: change the pointer, or change one of the chars it points at. Operate on the pointer part of the string: if (st == "Hi") Does st point at the string literal? (No.) sizeof The number of bytes in st (4) st = "Harmony" Make st point at a different word. Operate on the series of characters: strcmp(word, "Joy"); // Do the words have same letters? strlen(word); // The # of letters before the \0. (3) strcpy(word, "Joy"); // Copy Joy letters to word array.

... 21/26 The C String Library String Processing in C Basic C String Operations. size_t strlen( const char* s ); Returns the number of characters in the string s, excluding the null character on the end. Use subscript and = to modify individual chars in the middle of a string. Subscript can be used for an array of chars, and also for a pointer to an array of chars. When subscripting a pointer, the subscripts are relative to the slot the pointer points at. If two string pointers point into the same array of chars, they can both be used to modify the string stored there.

... 22/26 The C String Library String Processing in C Copying a C String char* strcpy( char* dest, const char* src ); Copies the string src into the array dest. We assume that dest has space for the string. char* strncpy(char* to,const char* src, size_t n) Copies exactly n characters from src into to. If fewer than n characters are in src, null characters are appended until exactly n have been written. char* strcat( char* dest, const char* src ); Appends the string src to the end of the string dest, overwriting its null terminator. It is a serious error is dest does not have space for the combined string. char* strncat(char* to, const char* src,size_t n) Same as strcat() except that it stops after copying n characters, then writes a null terminator.

... 23/26 The C String Library Compare and Search in C C String Comparisons. typedef char* cstring; cstring s1, s2; s1 == s2 asks if the pointers store the same memory address. To compare the chars that s1 and s2 point at, use strcmp(). int strcmp( const char* p, const char* q ); Compares string p to string q and returns a negative value if p is lexicographically less than q, 0 if they are equal, or a positive value if p is greater than q. int strncmp(const char* p,const char* q,size_t n) Same as strcmp() but returns after comparing at most n characters. It will return sooner if a null character happens sooner.

... 24/26 The C String Library Compare and Search in C Searching a String in C char* strchr( const char* s, int ch ); Searches the string s for the first (leftmost) occurrence of the character ch. Returns a pointer to that occurrence if it exists; otherwise returns NULL. char* strrchr( const char* s, int ch ); Searches the string s for the last (rightmost) occurrence of the character ch. Returns a pointer to that occurrence if it exists; otherwise returns NULL. char* strstr( const char* s, const char* sub ); Searches the string s for the first (leftmost) occurrence of the substring sub. Returns a pointer to the first character of that occurrence if it exists; otherwise returns NULL.

... 25/26 C++ String Functions A Few C++ String Functions String processing is easier. Suppose we have two C++ strings names str1 and str2: Use = to copy the contents of one string into another. string ss = st1; Use [ ] to access one letter in the string char ch = name[0]; Find the length of a string: int len = str1.size(); Get the first or last char in a string char c2 = name.front(); Set the first or last char in a string name.back() = y ;

... 26/26 C++ String Functions More C++ String Functions Concatenate two strings: cout << name +" "+ lname; Extract the C-string from the C++ string: char* cstr = str2.c_str(); Use == to compare two strings for equality. if (str1 == str2) cout <<"This is easy." <<endl; Use == to compare a string to a literal. if (str2 == "Ann") cout <<"Also easy."; Search a string for first occurrence of a character: int idx = str1.find_first_of("x") Search a string for last occurrence of a character: int idx = str1.find_last_of("x")