1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real.

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Advertisements

Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
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 © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 1 Overview 8.1 An Array Type for Strings 8.2 The Standard string.
C Strings. The char Data Type for Storing Characters The char data type can is used to declare a variable that can hold a single character. Examples:
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
Chapter 10.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
C-Strings A C-string (also called a character string) is a sequence of contiguous characters in memory terminated by the NUL character '\0'. C-strings.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Introduction to Computers and Programming Class 22 Character Arrays (Strings) Professor Avi Rosenfeld.
Programming Strings. COMP102 Prog. Fundamentals: Strings / Slide 2 Character Strings l A sequence of characters is often referred to as a character “string”.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
1 Chapter 10 Characters, Strings, and the string class.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
In Addition... To the string class from the standard library accessed by #include C++ also has another library of string functions for C strings that can.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
Array with base type char One character per indexed variable One extra character: '\0' Called ‘null character’ Delimiter of the string To declare a string,
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
9-1 Learning Objectives  An Array Type for Strings  C-Strings.
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.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 13 October 13, 2009.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
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.
String Class. C-style and C++ string Classes C-style strings, called C-strings, consist of characters stored in an array ( we’ll look at them later) C++
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.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
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
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Chapter 15 Strings as Character Arrays
Chapter 9 Strings. Learning Objectives An Array Type for Strings – C-Strings Character Manipulation Tools – Character I/O – get, put member functions.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
An Array Type For Strings. Two ways to represent strings – i.e. “Hello” cstring An array with base type char Older way of processing strings Null character.
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Chapter Characters, Strings, and the string class 10.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
Suyash Bhardwaj Dept. of Computer Science & Engineering Faculty of Engineering & Technology Gurukul Kangri University, Haridwar l1l1 UNIT 1 String Processing.
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
Fundamentals of Characters and Strings
Chapter 9 Strings Copyright © 2016 Pearson, Inc. All rights reserved.
7 Arrays.
Arrays and Pointers Reference: Chapter , 4.11 CMSC 202.
String What it is Why it’s useful
C-strings In general, a string is a series of characters treated as a unit. Practically all string implementations treat a string as a variable-length.
Chapter 9 Strings Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
C++ Programming Lecture 20 Strings
Presentation transcript:

1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real world data organization to the logical world in such a way that makes problems easy to understand and solve.  To make the link between program and real world clear  To make programs process data as efficiently as possible.

2 Algorithms The step by step sequence of instructions that operate on data structures for a specific purpose. The step by step sequence of instructions that operate on data structures for a specific purpose. Some data structures are better than others for data processing. Some data structures are better than others for data processing.

3 Silly example  Suppose we want a program that manipulates peoples names.  We could use the basic char data type as our data structure.  That is we could define 30 separate variables, char chr1, chr2, chr3 … chr30;  Then assign each one a character in a name.  This would be very clumsy and hard work and inflexible. A better data structure would be to create a string. A better data structure would be to create a string.  that enables manipulation of a string as a whole and as individual characters

4 String Data Structure Basic input and output Basic input and output Basic string processing Basic string processing Character by character input Character by character input Library functions Library functions Using Strings with functions Using Strings with functions Common errors Common errors

5 Fundamentals String literal – a sequence of characters in double quotes. String literal – a sequence of characters in double quotes.  “This is a string”, “Hello world”, “mydata.dat” A string is an array of characters. A string is an array of characters.  What is an array?  It is a data structure, a container, a way of organising data.  It is a chunk of memory, a series of adjacent bytes.

6 String Arrays A sequence of characters plus one special character. A sequence of characters plus one special character.  The end of string character.  A named constant NULL  NULL takes the value of ‘\0’  E.g. the string “Good Morning!” has one extra character the NULL character which is not displayed.

7 “Good Morning!” GodoMorning!\O Each box is one byte of memory the string takes up one continuous chunk of memory the sting takes up 14 bytes not 13 the end of string character acts as a sentinel (a marker for many string processing problems)

8 String Variables Think of a name for your variable Think of a name for your variable e.g. FirstName, StreetName, Town, Country etc. e.g. FirstName, StreetName, Town, Country etc. Think about the maximum characters needed to store. 5, 10, 80, 100, etc. Think about the maximum characters needed to store. 5, 10, 80, 100, etc. Then add one to that number for the NULL end of string character. Then add one to that number for the NULL end of string character. Declare string variable as an array of characters. using special array notation. Declare string variable as an array of characters. using special array notation.

9 Example char FirstName[20]; //able to store a string of 19 chars char LastName[20]; //able to store a string of 19 chars char Sentence[80]; //able to store a string of 79 chars char word[10]; //able to store a string of 9 chars Unititialised string variables. Only memory allocated. They do not contain any useful information. NO this is not an error! Take the string word for instance. It appears that 10 spaces have been allocated, enough for 10 characters? however strings of this sort require one extra space for the end of string character. Which means you only have 9 “usable” spaces.

10 Example – declaration plus initialisation char S[14] = “Chris”; char S[14] = “Chris”; initialising this way automatically places a NULL character at the end of the string. Compare with unititialised version char S[14]; char S[14]; Chirs\0 ?????????????? s[0]s[1]s[3]s[2]s[4]s[5]s[6]s[7]s[8]s[9]s[10]s[11]s[12]s[13] note max subscript 1 less than length of string

11 String Indexes A string has a certain length. A string has a certain length. That is, the number of characters not including NULL. This is not the same as the size of the array. That is, the number of characters not including NULL. This is not the same as the size of the array. The name of the string is a reference to the address of the first character. The name of the string is a reference to the address of the first character. We can access any character we wish by using the square bracket notation. We can access any character we wish by using the square bracket notation.  e.g. FirstName[0] allows us to access the first character in the string FirstName. FirstName[1] accesses the second character, FirstName[2] the third and so on.  Problem this array index or array subscript is confusing.  One off problems

12 Demo 1 Accessing elements of a string Accessing elements of a string  char message[14] = “Good Morning!”; Illustrate access of unititialised string. Illustrate access of unititialised string. Illustrate going past the end of string character but still in bounds of array. Illustrate going past the end of string character but still in bounds of array. Illustrate going off the end of the array Illustrate going off the end of the array Illustrate difference between strlen and sizof Illustrate difference between strlen and sizof

13 Basic input of strings Using extraction operator (with cin or a file stream). Using extraction operator (with cin or a file stream).  cin >> FirstName;  fin >> FirstName; Problem Problem  Extraction operator uses a space as terminator Note no square brackets [ ]

14 More string input tools cin.get() or fin.get() cin.get() or fin.get()  extracts a single character inlcuding white space! cin.getline() or fin.getline() cin.getline() or fin.getline()  extracts a whole line of characters including white space.

15 cin.get() cin.get() returns a character entered at the keyboard. cin.get() returns a character entered at the keyboard. e.g. to enter a number of characters at the keyboard including spaces and assign then to individual string elements. const int MAXCHARS = 80; char line[MAXCHARS+1]; int i=0; do { line[i] = cin.get(); i++; } while (line[i-1] != ‘\n’ && i < MAXCHARS); line[i] = ‘\0’; DO DEMO 2

16 Using getline() basic use of getline needs three arguments. cin.getline(stringvar,lengthvar, stop_char)   stringvar is the name of a string variable.   lengthvar is the name of an integer variable that denotes the maximum number of characters to be read. A literal int can be used. extraction stops when stop_char encountered.   cin.getline(LastName,14,’\n’); extracts up to 14 characters from the keyboard, stops extraction when ‘\n’ encountered

17 Demo 3 Creating string variables Creating string variables Inputting with extraction operator Inputting with extraction operator  problems with spaces Using getline() Using getline()

18 #include int main() { const int MAXCHARS 80; char message[MAXCHARS+1]; cout << “Please enter a message : “; cin.getline(message,MAXCHARS,’\n’); cout << “Your message is : “ << message << endl; return 0; }

19 Using = and == with strings You cannot use these operators in the same way as you would with basic data types. You cannot use these operators in the same way as you would with basic data types. E.g. E.g. char Name[10]; Name = “Thomas”; Assignment Illegal! Only allowable in declaration

20 Assignment of strings Use strcpy() library function Use strcpy() library function Needs Needs #include strcpy(destination, source); e.g. e.g. strcpy(FirstName,”Chris”); “Assigns” the string “Chris” to FirstName

21 Checking for equality The statement The statement if (FirstName1 == FirstName2) { do something.. } is not illegal. It does NOT test whether FirstName1 is the same as FirstName2 Use library function which again needs Use strcmp() library function which again needs # include

22 Comparisons of Strings strcmp(string1, string2) returns an integer, strcmp(string1, string2) returns an integer,  > 0 if string1 is “bigger” than string2  < 0 if string1 is “smaller” than string2  0 (False) if string1 is the same as string2 It compares each string a character at a time. It compares each string a character at a time. typical use if (strcmp(FirstName, “Chris”) == 0) cout << “My Name” << endl; True

23 Finding the length of a string A very important task in string processing is to find the number of characters in a string. A very important task in string processing is to find the number of characters in a string. To set bounds of loops to process the string. To set bounds of loops to process the string. Remember the declaration gives the maximum number of characters. Remember the declaration gives the maximum number of characters.  The NULL character \0 marks the end of a string.  We want the count up to the NULL character.

24 Library function strlen() Needs Needs #inlcude This function returns the length of a string char FirstName[40]; int size; strcpy(FirstName, “Christopher”); size = strlen(FirstName); for (int i=0;i<size; i++) FirstName[i] = “*”; cout << FirstName << endl;

25 String Processing Loops, Loops and Loops Loops, Loops and Loops  for loops, while loops, do while loops E.g. To fill a string my_string, with ‘*’ characters E.g. To fill a string my_string, with ‘*’ characters while loop version int i = 0; while (my_string[i] != ‘\0’) { my_string[i] = ‘*’; i++; } for loop version for (i=0; my_string[i] != ‘\0’; i++){ my_string[i] = ‘*’; i++; } NOTE THIS IS DANGEROUS since no check is made on whether there is a NULL character

26 Safer Version while loop version int i = 0; while (my_string[i] != ‘\0’ && i < MAXCHARS) { my_string[i] = ‘*’; i++; } I leave it as an exercise to adapt the for loop version to a safe version.

27 CAUTION When manipulating strings make sure you do not lose or replace the NULL character. When manipulating strings make sure you do not lose or replace the NULL character. Make sure that the NULL character is in the correct place. That is, one position after the last character in string. Make sure that the NULL character is in the correct place. That is, one position after the last character in string.

28 Strings as function arguments Passing a string to a function. Passing a string to a function. e.g. size = strlen(mystring); Notice no square brackets [ ] are used in the call. What is passed?

29 A bit of technical stuff. Take a deep breath! The string variable name without square brackets contains the address in memory of the first position of the string. The string variable name without square brackets contains the address in memory of the first position of the string. All that is passed is an address! All that is passed is an address!  a variable that can store addresses is called a pointer. When an array is passed to a function all that is passed is the address of the first element of the array. When an array is passed to a function all that is passed is the address of the first element of the array.

30 How does the function know the size of the string? How does the function know the size of the string? The standard functions use the NULL character as a sentinel. The standard functions use the NULL character as a sentinel. They have a precondition that the strings passed are properly formed They have a precondition that the strings passed are properly formed  A dangerous assumption. It would be safer if we provided information about the sizes of strings being manipulated. It would be safer if we provided information about the sizes of strings being manipulated. E.g. What happens if we attempt to copy a string with 50 characters into a string that can only take 5 characters max? E.g. What happens if we attempt to copy a string with 50 characters into a string that can only take 5 characters max?  memory is overwritten!

31 Creating your own functions that operate on strings: e.g. A safe string copy function Prototype Prototype void my_string_copy(char target[], char source[], int target_size); Notice syntax of prototype. The size of target and source is not provided. Since all that is passed is the address of the first element. target and source receive addresses. This is similar to pass by reference. Note also choice of generic names for the parameters, that do not conflict with identifiers else where in your program

32 Function Definition Function Definition void my_string_copy(char target[], char source[], int target_size) { int new_length; // temporarily hold length of source string new_length = strlen(source); // can target hold a string this long? if (new_length > (target_size-1)) // allow for NULL new_length = target_size; // fit in all we can // copy character by character for (int i = 0; i < new_length; i++) target[i] = source[i]; target[i] = ‘\0’;//add the NULL to the end of target }

33 Putting it all together #include //prototype void my_string_copy(char target[], char source[], int target_size); int main() { char shortSTR[5]; //holds up to 4 chars char longSTR[] = “This is a long string”; my_string_copy(shortSTR,”Hello”,5); cout << shortSTR << “STRING ENDS HERE. \n”; my_string_copy(shortSTR,longSTR,5); cout << shortSTR << “STRING ENDS HERE. \n”; return 0; } void my_string_copy(char target[], char source[], int target_size) { int new_length; // temporarily hold length of source string new_length = strlen(source); // can target hold a string this long? if (new_length > (target_size-1)) // allow for NULL new_length = target_size; // fit in all we can // copy character by character for (int i = 0; i < new_length; i++) target[i] = source[i]; target[i] = ‘\0’;//add the NULL to the end of target } DO DEMO 4

34 Summary We have been discussing strings in particular the Cstring form. This sort of string uses a NULL sentinel We have been discussing strings in particular the Cstring form. This sort of string uses a NULL sentinel The string is an array or characters The string is an array or characters You cannot assign with = operator, use strcpy() or write your own. You cannot assign with = operator, use strcpy() or write your own. You cannot compare with == use strcmp() or write your own. You cannot compare with == use strcmp() or write your own. Be careful when operating on strings not to write past the end of the string! Be careful when operating on strings not to write past the end of the string!  protect with a check for length. Be careful not to overwrite the NULL character, or forget to insert it. Be careful not to overwrite the NULL character, or forget to insert it. When strings are used with functions it is like passing by reference. There is no pass by value for arrays! When strings are used with functions it is like passing by reference. There is no pass by value for arrays! Note there is another way of defining strings using the string class (not covered here) Note there is another way of defining strings using the string class (not covered here)