Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
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 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
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.
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
ECE Application Programming Instructor: Dr. Michael Geiger Spring 2012 Lecture 31: PE5.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
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.
Chapter 9 Strings Instructor: Alkar / Demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
Chapter 9 Character Strings
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Topic 10 - Strings.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 8 - Characters and Strings Outline 8.1Introduction.
N-1 University of Washington Computer Programming I Lecture 19: Strings © 2000 UW CSE.
CS1061 C Programming Lecture 14: Strings A. O’Riordan, 2004.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Strings.
To remind us We finished the last day by introducing If statements Their structure was:::::::::
CS Nov 2006 C-strings.
Data Structure and C Part-6. Naming a Function Any valid variable-name can be given to the user-defined function. The main program itself is considered.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
1. An array is a collection of a fixed number of components wherein all of the components are of the same type Example: Suppose that there is a list of.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
Introduction to C programming
CHAPTER 8 CHARACTER AND STRINGS
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
February 14, 2005 Characters, Strings and the String Class.
Characters and Strings File Processing Exercise C Programming:Part 3.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Characters, Strings, And The string Class Chapter 10.
Chapter 8 Strings. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data structure using arrays of.
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.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
13. 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.
Slides from Shane Griffith (TA and guest instructor in Fall 2008) CprE 185: Intro to Problem Solving.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
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).
UniMAP SEM I - 10/11EKT 120 Computer Programming1 Lecture 8 – Arrays (2) and Strings.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Chapter 9 Strings J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of Technology.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Characters and Strings
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.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
13. 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.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
STRINGS STRINGS IN C FUNCTIONS DEALING WITH CHARACTERS FUNCTIONS DEALING WITH STRINGS.
Lesson #7 Arrays‏.
C Characters and Strings
Strings CSCI 112: Programming in C.
Characters and Strings
C Characters and Strings
Fundamentals of Characters and Strings
CSE 303 Lecture 14 Strings in C
Chapter 8 - Characters and Strings
Week 9 – Lesson 1 Arrays – Character Strings
CprE 185: Intro to Problem Solving (using C)
C Characters and Strings
Introduction to Problem Solving and Programming
Presentation transcript:

Arrays II (Strings)

Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’}; Ex. scanf(“%c”, &ch); Ex. ch = ‘A’; Ex. for (i=0;i<5; i++) printf(“%c”, chb[i]);

Strings There is no string type in C. Instead, to approximate strings, we will use arrays of characters. To transform a simple array of characters into a string, it must contain the '\0' character in the last cell. A string is an array of characters with the last character of the array as the “null” character. char chs[]={‘h’,’e’,’l’,’l’,’o’,’\0’}; printf(“%s”, chs);

Strings Note that '\0' is one character. It is called the null character or the end-of-string character. char chs[]={‘h’,’e’,’l’,’l’,’o’,’\0’}; printf(“%s”, chs); Compare with previous example: char cha[]={‘h’,’e’,’l’,’l’,’o’}; for (i=0;i<5; i++) printf(“%c”, cha[i]);

Strings To declare a string and initialize it we could do it the same way as before: char city[ ] = {'T', 'o', 'r', 'o', 'n', 't', 'o'}; char city[ ] = {'T', 'o', 'r', 'o', 'n', 't', 'o', '\0'}; But there is a simpler way: char city[ ] = “Toronto”; The result is exactly the same. By using the simpler way, the '\0' is added automatically at the end. 'T''o''r''o''n''t''o''\0' city

“X” and 'X' Double quotes “ “ represent a string, A single quote ' ', one character. '?' is the single character ? But “?” is an array size 2 containing the '?' character and the '\0' character. A string constant can be represented in double quotes (remember “This is my first C program.” ?).

First C program A simple C program #include int main() { printf(“This is my first program”); return 0; }

Filling a string We have already seen how to fill a string by initializing it in a declarative statement. Now how to do it in an executable statement. char city[30]; To fill a string from standard input (scanf), we use a special placeholder for strings %s. scanf (“%s”, city); (Notice the absence of &. It is not necessary here since city is already a pointer)

Exercise I Write a C program that will ask a user to input his/her first name and last name from the keyboard. Print out the names (both last and first) on the standard output using strings.

Arrays of strings It is also possible to have arrays of strings. Since strings are themselves arrays, then we need to add a second size. An array of strings is in fact an array with two dimensions, width (columns) and height (rows).

Array of string char city[3][10]; 'T'‘o'‘r'‘o'‘n'‘t'‘o'‘\0' ‘O'‘t' ‘a'‘w'‘a'‘\0'‘H'‘a'‘l'‘i'‘f'‘a'‘x'‘\0' city

Array of string char list_cities[100][15]; will be able to contain 100 city names with a maximum of 14 letters per city. Why not 15?

Arrays of strings (cont.) Example: An array containing the names of the months. char months [12][10] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”};

Filling a string There is one problem with the %s placeholder when used with scanf (or fscanf). It considers the space as a delimiter. Therefore, if for a city name you enter Los Angeles, you will get only Los stored in the string. The solution is to use a function from the string library (string.h) called gets (or fgets if you read from a file). That function only considers the “enter” key as delimiter not the space. Instead of scanf (“%s”, city); you use gets (city); Instead of fscanf (in, ”%s”, city); you use fgets(city, size, in);

Printing a string The space problem does not occur with printf. If the city is “Los Angeles” then a printf (“%s”, city); will print out the entire city name. There is a puts function in the string library as an alternative to printf but its use is less imperative than the gets.

Exercise Write a C program that will contain an array to store 3 strings. Let the user input the three strings and print out the three strings on the screen. The Three strings will be the last names of your group members you need to do this exercise with a group of 3 people

String Constant Macros A string can also be a constant macro like: #define ERROR “Sorry – Invalid Operation” #define STRING “This is a string constant” #define PI 3.14

String functions We just learned about gets, but there are many more useful functions in the string.h library. strcat: the string concatenation function. strcat needs two arguments (two strings) and then adds up the two strings: char s1[ ] = “The quick “; char s2[ ] = “brown fox.”; strcat (s1, s2); printf (“New string is: %s”, s1); /* notice that the new string is placed in the first argument */ New string is: The quick brown fox.

String functions strncat: the same thing as strcat except that it has a third argument specifying how many characters to the second string to append: char s1[ ] = “The quick “; char s2[ ] = “brown fox.”; strncat (s1, s2, 3); printf (“New string is: %s”, s1); /* notice that the new string is placed in the first argument */ New string is: The quick bro

String functions strcmp: this function performs a string comparison between two strings. It uses the ASCII code to compare. It starts with the first character and then continues character by character. When characters are all identical, the longer string is the greater one. It returns 0 if the two strings are identical, a negative number if the first string is smaller than the second and a positive number when the first string is larger than the second. char city1[ ] = “Toronto”; char city2[ ] = “Vancouver”; if (strcmp(city1, city2) < 0) /* condition is true here because “T” is smaller than “V” /*

String functions strncmp: identical to strcmp except that a third argument specifies how many characters to compare. char city1[ ] = “Mexicali”; char city2[ ] = “Mexico City”; if (strcmp(city1, city2) < 0) /* condition is true here because “a” is smaller than “o” /* if (strncmp(city1, city2, 4) < 0) /* condition is false here, the answer would be 0 because the first 4 characters are identical /*

String functions strcpy: the function to transfer a string into a variable. Equivalent to the assignation operator. With strings you cannot do city=”Toronto”; in an executable statement. To do an assignment we use strcpy. char city[10], city2[10]; strcpy (city, “Toronto”); /* places “Toronto” into city /* strcpy (city2, city); /* places “Toronto” into city2 /* 'T''o''r''o''n''t''o''\0'?? city

String functions strncpy: strncpy is like strcpy except for a third argument specifying how many characters to copy. char city[10], city2[10]; strcpy (city, “Toronto”); /* places “Toronto” into city /* strncpy (city2, city, 4); /* places “Toro” into city2 /* 'T''o''r''o''\0'????? city

String functions strlen: the strlen function returns the length of the string not counting the null character. char city[10]; strcpy (city, “Toronto”); /* places “Toronto” into city */ printf (“%d”, strlen (city)); /* displays 7 on the screen */

Exercise Write a C program that will able to compare two strings and print out the larger string.

Passing a string to a function Passing a string to a function is the same thing as passing an array of numerals. We pass only the pointer to its first cell. Here is a function that takes in a string a counts the number of vowels (a,e,i,o,u) in it. Notice that contrary to numerical arrays, we don't need to pass the size because for strings it is easy to determine its size from inside the function (which is not possible for arrays of numerals).

Passing a string to a function int count_vowels (char string[]) { int nv=0, i; for (i=0; i<strlen(string); ++i) if (string[i]=='a'||string[i]=='e'||string [i]=='i'||string[i]=='o'||string[i]=='u ') nv = nv + 1; return (nv); }

Passing a string to a function The main program would look like this: int main (void) { char s[100]; int vowels; printf ("Enter a sentence: "); gets (s); vowels = count_vowels (s); printf ("Thre sentence contains %d vowels.\n", vowels); return (0); }

Character functions Functions from the string.h library work one entire string at a time. Character functions, present in the ctype.h library work one character at a time only. Here is a list of the character functions: isalpha returns true if the character is in the range of A-Z or a-z. isalnum returns true if the character is in the range of A-Z or a-z or 0-9. isdigit returns true if the character is in the range of 0-9.

Character functions isspace returns true if the character is a space. ispunct returns true if the character is a punctuation character. islower returns true if the character is in the range of a-z. isupper returns true if the character is in the range of A-Z.

Character functions tolower transforms the letter into a lowercase letter. toupper transforms the letter into an uppercase letter.

End of lesson