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

Similar documents
Introduction to string

Chapter 8 - Characters and Strings

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

Scientific Programming in C V. Strings

C: How to Program. Week /May/28

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University


Chapter 8 C Characters and Strings

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

C Characters and Strings

Strings and Library Functions

Chapter 8 Character Arrays and Strings

ONE DIMENSIONAL ARRAYS

by Pearson Education, Inc. All Rights Reserved.

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

8. Characters, Strings and Files

Intermediate Programming, Spring 2017*

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

Characters and Strings

C-LANGUAGE CURRICULAM

Introduction to C/C++ Lecture 5 - String & its Manipulation

Input/Output Week 5:Lesson 16.1

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

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

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

LESSON 4. The DATA TYPE char

Fundamentals of Programming. Lecture 11: C Characters and Strings

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

Computers Programming Course 11. Iulian Năstac

Computers Programming Course 10. Iulian Năstac

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

CS1100 Introduction to Programming

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

There are functions to handle strings, so we will see the notion of functions itself in little a detail later. (Refer Slide Time: 00:12)

CCE1111 Programming for Engineers [C Programming Language]

Fundamentals of Programming & Procedural Programming

Strings. Chuan-Ming Liu. Computer Science & Information Engineering National Taipei University of Technology Taiwan

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

CS107 Spring 2019, Lecture 4 C Strings

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

Multiple Choice Questions ( 1 mark)

C mini reference. 5 Binary numbers 12

CS107, Lecture 4 C Strings

THE FUNDAMENTAL DATA TYPES

Strings. Daily Puzzle

Unit 4. Input/Output Functions

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

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

A First Book of ANSI C Fourth Edition. Chapter 9 Character Strings

Model Viva Questions for Programming in C lab

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

ARRAYS(II Unit Part II)

ANSI C Programming Simple Programs

SU 2017 May 11/16 LAB 2: Character and integer literals, number systems, character arrays manipulation, relational operator

Overview. Concepts this lecture String constants Null-terminated array representation String library <strlib.h> String initializers Arrays of strings

Computers Programming Course 5. Iulian Năstac

LAB7 : Characters and Strings

Introduction to Computing Lecture 03: Basic input / output operations

AWK - PRETTY PRINTING

Strings. Steven R. Bagley

Computer Programming: Skills & Concepts (CP) Strings

C Strings. Abdelghani Bellaachia, CSCI 1121 Page: 1

Personal SE. Functions, Arrays, Strings & Command Line Arguments

BITG 1113: Array (Part 2) LECTURE 9

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.

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

Course organization. Course introduction ( Week 1)

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

C-String Library Functions

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

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

Should you know scanf and printf?

Programming for Engineers Introduction to C

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

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

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

UNIT-I Input/ Output functions and other library functions

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

Number Systems, Scalar Types, and Input and Output

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

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture5 C Characters and Strings

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

بسم اهلل الرمحن الرحيم

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

File Handling in C. EECS 2031 Fall October 27, 2014

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

ELEC / COMP 177 Fall Some slides from Kurose and Ross, Computer Networking, 5 th Edition

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

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

Exercise 1.1 Hello world

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

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

C Programming. Unit 9. Manipulating Strings File Processing.

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

Full file at C How to Program, 6/e Multiple Choice Test Bank

Transcription:

Chapter 9 Strings 9.1 Chapter Overview There is no data type in C called ʻstringʼ; instead, strings are represented by an array of characters. There is an assortment of useful functions for strings that are available in the C library by including the string header file at the top of your program: #include <string.h> In this chapter, several of the more commonly performed operations on strings are looked at in detail, including concatenation, string copying, extracting a portion of a string, and determining if two strings are equal. 9.2 Declaring and Initializing a String A word in C, for example, the following hello! might be declared as: char word[] = { h, e, l, l, o,! }; which would be a character array containing those 6 characters (and only those 6 characters). In C, a special character is used to signal the end of a string known as the null character, which is represented by ʻ\0ʼ. So, the following would be done to declare the word above including the null character: char word[] = { h, e, l, l, o,!, \0 }; which would make it 7 characters long. By using this special character, this allows you to deal with strings without always having to know how long they are (variable length character strings) as soon as the null character is reached, it is at the end of the string. (One of the functions included in string.h is strlen() more about that later.) Defining it that way in the above example is the same as the following: char word[] = { hello! }; or char word[] = hello! ; each of which results in a 7 character word including the null character at the end. If you are explicitly specifying the size of the array, donʼt forget the null character: char word[7] = hello! ; With the above declaration, the compiler will have enough room to place the ʻ\0ʼ character at the end, whereas, the following would not: char word[6] = hello! ; If the compiler does not have enough room for the ʻ\0ʼ character at the end, it just leaves it out, and it doesnʼt complain about it either. A character array that does not have the null character ʻ\0ʼ at the end, it no longer acts like a string and you may get unpredictable results. In C, character string constants are automatically terminated by the null character. With the following: printf( I love programming in C! \n ); the null character is automatically placed at the end after the newline character, thereby enabling the printf function to determine when it has reached the end of the string. With this array declaration: char s[10]; the c- string variable s will be able to hold up to 9 characters plus one null character. None of the elements of the array have an initial default value:

With this array declaration and initialization: char s[10] = Hi Mom! ; the c- string variable s will be stored as: When declaring a character array, we usually try to specify a size that is large enough to hold the maximum size string we wish to store plus one for the null character. An initial value that is too long to fit in the specified size will result in a syntax error. 9.3 Displaying Strings Another useful feature in C involves the display of strings. You can use the special format character %s inside a printf to display an array of characters that is terminated by the null character. So the following string: char word[7] = hello! ; can be displayed with the following statement: printf( %s\n, word); The printf assumes that when it sees a %s, the argument is a character string that is terminated by the null character. 9.4 More on Constant Strings If you are initializing a long character string, you can break it up onto two lines, like the following, using a backslash character at the end of each line that is to be continued: char letters[] = { abcdefghijklmnopqrstuvwxyz\ ABCDEFGHIJKLMNOPQRSTUVWXYZ }; or by this method, using separate strings, which the compiler automatically concatenates: char letters[] = { abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ }; Because the compiler automatically concatenates adjacent strings, the following three printf statements all pass a single argument to printf: printf ( I love programming in C! \n ); printf ( I love programming in C! \n ); printf ( I love programming in C! \n ); 9.5 The NULL String A character string that contains no characters is called a null string. It has a length of zero. This can be used, for example, as a way for the user to tell the program when he is done entering text by having him hit the enter key an extra time after the last line of text has been entered, as with Program 9.8 in the book, pages 212-214. 9.6 Inputting Character Strings The scanf function can be used with the %s format characters to read in a string of characters up to a blank space, tab character, or the end of the line, whichever occurs first. The following has the effect of reading a character string typed into your terminal window and storing it inside the character array string. char string[81]; scanf ( %s, string); There are two things to note. First, there is no & in front of string. This is because it is an array and the array name already points to the location in memory for that item.

Second, notice the size of the array. You can declare an array like this perhaps larger than what you think youʼll need, to be sure there is sufficient space for the string. When the string is read and put into that array, if it is shorter than 81 characters, the null character will be put at the end of the string. Then, if you use a printf statement to print it out, no matter how much shorter it is, the printf stops as soon as it reaches the null character, so it doesnʼt matter that the array was declared to be larger than the actual string. scanf ( %s%s%s, string1, string2, string3); The above line will read in three strings and store then into the strings named string1, string2, & string3. So, the user can enter three strings separated by a space, tab, or each on a separate line. It will wait until three strings have been entered. When handed the %s format, scanf continues to read until the user hits the space bar, tab key, or enter. If the user were to enter more than 80 characters without pressing the spacebar, tab key, or enter, scanf overflows one of the character arrays, which might cause the program to terminate abnormally or cause unpredictable things to happen. If you want to make sure this doesnʼt happen, you can place a number after the % in the scanf format string, which tells scanf the maximum number of characters to read, like the following: scanf ( %80s%80s%80s, string1, string2, string3); 9.7 getchar and gets Functions The standard library provides several functions for reading and writing single characters and entire character strings. getchar can be used to read in a single character from the terminal. Why do you need this when you can use scanf with the format characters %c, you ask? getchar is defined to read in a single character, so it doesnʼt need any arguments. So you can have a variable of type char called character, and then assign that to getchar(), as with the following: char character;... character = getchar(); getchar actually returns an integer, but assigning it to a variable of type char automatically converts it from an int to a char. gets is another function available from the library, which is used to read in a single line of text. The newline character signals the end of the line, and the null character is placed at the end of the array (replacing the newline character) to terminate the character string. If successful, it returns the string and places it into the argument. The gets function is dangerous because it does not check the length of the input and will overrun the string if too long. On many machines, gcc will produce a warning message when using gets. char input_string[100]; gets(input_string); Program 9.6, page 207, shows how to implement a function similar to the gets function using getchar.

9.8 Character Output, putchar and puts Using the %s format string with printf allows you to print the value of a variable that is a c- string to the screen. char string[81]; scanf ( %s, string);... printf ( %s \n, string); putchar writes one character at a time to standard output. char msg[] = dlrow olleh ; int ndx; // print dlrow olleh printf ( %s \n, msg); // print Hello World for (ndx = (int)strlen(msg) 1; ndx >= 0; ndx--) putchar(msg[ndx]); printf( \n ); puts writes a string to standard output. A newline character is written in place of the null character. This means you will always get a new line character when using puts. char hello[] = Hello ; puts (hello); printf( -----\n ); /* output: */ Hello ----- 9.9 Escape Characters Some of the escape characters from page 215: \a audible alert (sounds a bell) \b backspace \f form feed \n newline \r carriage return \t horizontal tab \v vertical tab \\ backslash \ double quotation mark \ʼ single quotation mark \? question mark Each escape character is counted as a single character. So the following string contains 9 characters: \033\ Hello\ \n (033 is the ASCII escape character)

9.10 Character Operations Character constants and variables in C are treated as an integer value. In ASCII, the character ʻaʼ has the value of 97, ʻbʼ a value of 98, etc. Therefore the expression c >= a is TRUE (nonzero) for any lowercase character contained in c. The following expression could be used to test if a letter is a lower case letter: if c >= a && c <= z which would be the same as the following: if c >= 97 && c <= 122 printf ( %i, a ); would print 97 printf ( %c, a ); would print a c = a + 1; printf ( %c \n, c); would print b This can be very useful to convert characters ʻ0ʼ through ʻ9ʼ to their corresponding numerical values 0 through 9. Because ʻ0ʼ has the numerical value of 48 in ASCII, you can subtract ʻ0ʼ from it to get the numerical value of 0. Same with any other character digit: ʻ1ʼ ʻ0ʼ would result in the numerical value of 1 (49 48); ʻ2ʼ ʻ0ʼ would result in the numerical value of 2 (50 48); etc. This makes it easy to convert a character string consisting of digits to its equivalent numerical representation. There is a function available in the library called atoi() that converts the string sent to it to an integer and returns that integer value. There are also other string conversion functions available as well; Appendix B shows some of the common ones, pages 483-484; they are in the <stdlib.h> header file. Program 9.11 on page 228 shows an implementation of a string conversion, called strtoint, demonstrating how a string can be converted to its corresponding integer value. 9.11 String Library C provides a string library that contains functions for manipulating strings. If you #include <string.h> in your program, you can use functions like: strcpy, strcat, strlen, strcmp, strchr, strtok, memset, memcpy, among others. You can reference your book or Google string.h for more information on these and other functions in the string library. strlen returns the length of the string (not including the null character). The function returns a size_t data type, so you may need to typecast the return type depending on where it appears. char helloworld[] = Hello World ; printf( %d, (int)strlen(helloworld)); // the above will print number 11

strcpy copies a string value into a character array variable. Strings are not like other variables you cannot assign a value to an array: char msg[10];... msg = Hello ; // CANNOT DO THIS!!! To assign a value to an array after it has been declared, you can do one of two things. You can assign each element of the array individually: char msg[10];... msg[0] = H ; msg[1] = e ; msg[2] = l ; msg[3] = l ; msg[4] = o ; msg[5] = \0 ; Or, you can use the strcpy function: char msg[10];... strcpy(msg, Hello ); There is also a strncpy function: strncpy(destination, source, limit) This has a third argument, which is a limit of the number of characters from the source to copy. If the limit is reached, no null character is placed in the destination, however.

strcmp compares two strings to check for equality. You cannot use == operator to compare two strings: char hello[] = Hello ; char help[] = Help ; if (hello == help) // CANNOT DO THIS!!! You must use strcmp: strcmp(string1, string2) The function compares the same two elements from each string (the first character from string1 compared to the first character from string2; the second character from string1 compared to the second character from string2; etc.) This function returns a 0 if there is no difference between the two strings (if they are the same). It returns a value <0 if the first non- matching character from string1 comes before (alphabetically) the one from string2. It returns a value >0 if the first non- matching character from string1 comes after the one from string2. char hello[] = Hello ; char help[] = Help ; if (strcmp(hello, help) == 0) printf( They are the same string\n ); else if (strcmp(hello, help) < 0) printf( hello comes before help\n ); else if (strcmp(hello, help) > 0) printf( hello comes after help\n ); // will print: hello comes before help strcat concatenates two strings together, i.e. appends one string onto the end of another. Be careful when concatenating words it does not automatically add spaces in between the strings. strcat(destination, source) char msg1[30] = Hello ; char msg2[30] = Hello ; strcat(msg1, World ); // result: HelloWorld strcat(msg2, World ); // result: Hello World