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.

Slides:



Advertisements
Similar presentations
Problem Solving & Program Design in C
Advertisements

Introduction to C Programming
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.
Character String Manipulation. Overview Character string functions sscanf() function sprintf() function.
Character String Manipulation. Overview Character string functions sscanf() function snprintf() function.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
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.
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.
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 10.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
Chapter 8 Arrays and Strings
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
EPSII 59:006 Spring Introduction Fundamentals of Strings and Characters Character Handling Library String Conversion Functions Standard Input/Output.
Introduction to C programming
CHAPTER 8 CHARACTER AND STRINGS
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
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.
Chapter 9 Formatted Input/Output Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
EPSII 59:006 Spring Introduction In this lecture  Formatted Input/Output scanf and printf  Streams (input and output) gets, puts, getchar, putchar.
Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
CNG 140 C Programming (Lecture set 9) Spring 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.
CS 162 Introduction to Computer Science Chapter 17 C++ String Objects Herbert G. Mayer, PSU (Copied from Prof. Phillip Wong at PSU) Status 11/30/2014.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
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’};
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
Chapter 8 Strings. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data structure using arrays of.
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:
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.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Strings, Pointers and Tools
CMSC 104, Version 8/061L25Strings.ppt Strings Topics String Libraries String Operations Sample Program Reading Sections
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
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.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
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.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
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.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
1 Chapter 8 – Character Arrays and Strings Outline 8.1Introduction 8.2Declaring and Initializing String 8.3Input/output of strings 8.4String-handling Functions.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Lecture 8 String 1. Concept of strings String and pointers
A First Book of ANSI C Fourth Edition
Strings A string is a sequence of characters treated as a group
CS111 Computer Programming
Chapter 2 Array and String Visit to more Learning Resources.
Strings #include <stdio.h>
Presentation transcript:

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 a string literal, is anything enclosed in double quotation marks. printf (“Hello world”); To use a double quotation mark within a string, precede the quotation mark with a backslash (\) printf ( “\”Run, Spot, run!\” exclaimed Dick.\n” );

Introduction C standard library provides many functions specifically designed to work with strings. Reading and writing strings. Combining strings together. Copying one string to another. Comparing strings for equality. Extracting a portion of a string 3

Declaring and initializing string variables The only support for strings in the C is that the compiler will translate a quoted string constant into a null-terminated string, which is stored in static memory. The general form of declaration of a string variable is char string_name[size]; C does not support strings as a data type string length Examples: char city[10]; char name[30]; A string is a char array terminated with a null character (\0). char city[9] = ”Seoul”; char city[9] = {‘S’, ‘e’, ‘o’, ‘u’, ‘l’, ‘\0’}; [] array notation

Declaring and initializing string variables C permits us to initialize a character array without specifying the number of elements. char string [] = {‘G’, ‘O’, ‘O’, ‘D’, ‘\0’}; The string can be declared with much larger size then the string size In the initializer. char str[10] = “GOOD”. 5 GOOD\0 Set to zeros

Reading strings from terminal The familiar input function scanf function can be used with %s format specifier. char city[10]; scanf(“%s”, city); scanf() terminates its input on the first white space it finds. white space include: blanks, tabs new lines. If the following line of text is typed in at the terminal, NEW YORK Then only “NEW” will be read into the array address. The ampersand (&) is not required before the variable name. Because city is already address in memory where string is stored. NEW\0

Writing strings to screen The format %s in the printf function can be used to display an array of characters that is terminated by the null character. printf(“%s”, name); We can specify the precision with which the array is displayed. printf(“%10.4s”, name); or printf(“%-10.4s”, name); %10.4 indicates that the first four characters are to be printed in a field width of 10 columns. %-10.4, the string will be printed left-justified

Example The printf support feature that allows for variable field width. printf(“%*.*s\n”, w, d, string) printf the first d characters of the string in the field width of w.

Alternative to printf() We can use putchar() to output the values of a string. char ch = ‘A’; putchar (ch). We can use this function repeatedly to print out a string. char name [6] = “PARIS”; for (I = 0; I < 5; i++) putchar(name[i]); putchar(‘\n’) Another convenient way of printing string values is to use the function puts. puts (str);

Example

Each string has an address The %s format should print the string We. The %p format produces an address. So if the phrase "are" is an address, then %p should print the address of the first character in the string. 11 Very important example! Address of “are” Character located at the address “space travellers”

Missing Operators There is no string assignment operators. There are not string comparison operators. There are not string combination operators. However, there are built-in functions to do this common tasks. String functions prototypes defined in String functions prototypes defined in

Built-in String Functions String assignment. There is no ‘=‘ for string but there is strcpy( destination, source ) char name[ 25 ]; /* contains nothing */ strcpy( name, “Hilton” ); /* name now contains “Hilton” */ String comparison. There is no != for string but there is strcmp( strA, strB ); If strA comes after strB, the function returns a positive number. Is strB comes last, the function returns a negative number. If strA and strB are the same thing, the function returns a zero. result = strcmp( “CMSC”, “IFSM” ); /* negative */ result = strcmp( “IFSM”, “CMSC” ); /* positive */ result = strcmp( “CMSC”, “CMSC” ); /* zero */

Built-in String Functions (cont’d) String combination: strcat( destination, source ) The source is not changed. The destination contain exactly what it had before plus what was in the source. Nothing else is added. NOTE: If you are combining a first name and last name for a full name, you must use another strcat to add the space between them: strcpy( fullName, firstName); strcat( fullName, “ “ ); strcat( fullName, lastName );

Built-in String Functions (cont’d) Extracting words (tokens) from a string: /* get the first token (delimited by a blank) */ printf( "%s\n", strtok( str, " " ) ); /* This is more useful after you learn to use pointers. */

Built-in String Functions (cont’d) What if I want to get a menu choice, that is the numbers 1 to 4 or the char ‘q’? Use getchar( ) to get the menu choice, check for ‘q’ and if it is not, then convert it to a number. /* convert a string (ASCII) to an integer */ printf( "%d\n", atoi( "1234" ) ); /* convert a string (ASCII) to a float */ printf( "%f\n", atof( " " ) ); How long is the data in the string (not counting the null terminator)? stringSize = strlen( strA );

String Libraries #include files: #include /* needed by atoi( ) and atof( ) */ #include /* needed by str...( ) functions */

Sample Program

Sample Program Output string a is >Excellence< After strcpy(b, a), string b is now >Excellence< ============= String b = >Excellence< and is 10 characters long After strcat(b, " "), string b = >Excellence < and is 11 characters long After strcat(b, a), string b = >Excellence Excellence< and is 21 characters long strtok( b, " " ) gives Excellence

Sample Program Output (cont’d) ============= string a = Excellence string c = Failure strcmp( a, c ) gives -1 strcmp( c, a ) gives 1 strcmp( a, "Excellence" gives 0 After strcmp( "CMSC", "IFSM" ), result is -1 After strcmp( "IFSM", "CMSC" ), result is 1 After strcmp( "CMSC", "CMSC" ), result is 0

Sample Program Output (cont’d) ============= atoi( "1234” ) gives 1234 atof( " " ) gives

Other String Functions The statement copies first n characters of the source string s2 into the target string s1. Since the first n characters may not include the terminating null character, we have to place it explicitly in the 6 th position of s2 s1[n+1] = ‘\0’; This compares the left-most n characters of s1 to s2 and returns. a.0 if the are equal; b.Negative number if s1 sub-string is less than s2; and c.Positive number, otherwise. 23

Other String Functions Concatenate the left-most n characters of s2 to the end of s1. s1 s2 after(s1, s2, 6) s1 is a string to search within. s2 is the substring that you want to find. 24 HelloWorld\0 Korea KoreaWorld

Array Versus Pointer* You can use pointer notation to set up a string. const char *m3 = "\nEnough about me -- what's your name?"; This declaration is very nearly the same as this one: char m3[] = "\nEnough about me -- what's your name?" In short, initializing the array copies a string from static storage to the array, whereas initializing the pointer merely copies the address of the string. char heart[] = "I love Tillie!"; char *head = "I love Millie!"; The difference is that the array name heart is a constant, but the pointer head is a variable. head = heart; /* head now points to the array heart */ heart = head; /* illegal construction */

Example: reverse characters in an input string 26

Passing parameter to the main function 27