Chapter 8 Character Arrays and Strings

Similar documents
ONE DIMENSIONAL ARRAYS

Introduction to string

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

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

Chapter 8 C Characters and Strings

Strings and Library Functions

Computers Programming Course 11. Iulian Năstac

String can be represented as a single-dimensional character type array. Declaration of strings


Vidyalankar. F.E. Sem. II Structured Programming Approach Prelim Question Paper Solution

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

C does not support string data type. Strings in C are represented by arrays of characters.

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

Chapter 8 - Characters and Strings

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

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

by Pearson Education, Inc. All Rights Reserved.

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

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

UNIT-I Input/ Output functions and other library functions

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array?

C: How to Program. Week /May/28

ARRAYS(II Unit Part II)

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

8. Characters, Strings and Files

Intermediate Programming, Spring 2017*

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

9/9/2017. Prof. Vinod Mahajan

Fundamentals of Programming

Computers Programming Course 12. Iulian Năstac

LAB7 : Characters and Strings

Fundamental of Programming (C)

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.

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

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

Characters and Strings

Strings. Daily Puzzle

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

Course organization. Course introduction ( Week 1)

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

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

C Characters and Strings

C-String Library Functions

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

CS107 Spring 2019, Lecture 4 C Strings

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

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


1. Simple if statement. 2. if else statement. 3. Nested if else statement. 4. else if ladder 1. Simple if statement

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

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

Multiple Choice Questions ( 1 mark)

CS107, Lecture 4 C Strings

Important Questions for Viva CPU

1 Pointer Concepts. 1.1 Pointer Examples

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 10. Iulian Năstac

C-LANGUAGE CURRICULAM

Write a C program using arrays and structure

C Programming Language

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

Structured programming

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

C Programming Language Review and Dissection III

C Programming Multiple. Choice

It is necessary to have a single function main in every C program, along with other functions used/defined by the programmer.

UNIT -5 FUNCTIONS AND POINTERS

Computer Programming Unit v

Chapter 13. Strings. Introduction

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

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

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

UNIT 2 STRINGS. Marks - 7

Strings. Part III. 1) Introduction. 2) Definition. 3) Using Strings. 4) Input/Output. 5) Using string.h Library. 6) Strings as Function Parameters

Computer Science & Engineering 150A Problem Solving Using Computers

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

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

PDS Class Test 2. Room Sections No of students

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

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

Unit 4 Preprocessor Directives

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

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

CSC 2400: Computer Systems. Arrays and Strings in C

Department of Computer Applications

Chapter 10. Arrays and Strings

Contents. A Review of C language. Visual C Visual C++ 6.0

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

C mini reference. 5 Binary numbers 12

EM108 Software Development for Engineers

7.STRINGS. Data Structure Management (330701) 1

Procedural Programming

Procedural Programming & Fundamentals of Programming

Chapter 21: Introduction to C Programming Language

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

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

CSC 2400: Computer Systems. Arrays and Strings in C

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

Transcription:

Chapter 8 Character Arrays and Strings

INTRODUCTION A string is a sequence of characters that is treated as a single data item. String constant: String constant example. \ String constant example.\ \ includes double quote in the string. o printf( \ Well Done!\ ); output: Well Done! 2

DECLARING AND INITIALIZING STRING VARIABLES: C does not support strings as a data type. Strings are represented as character arrays. The general form of declaration of a string variable is: char string_name[size]; Example: char city[10]; char name[30]; Size = maximum number of characters in the string plus one (for NULL character \0 ) 3

DECLARING AND INITIALIZING STRING VARIABLES: Initialization: Example: 1. char city[18] = Ahmedabad Gujarat ; 2. char city[18] = { A, h, m, e, d, a, b, a, d,, G, u, j, a, r, a, t, \0 }; 3. char string[]={ G, o, o, d, \0 }; size is determined from list of values. 4. char str[10] = Good ; str G o o d \0 \0 \0 \0 \0 \0 4

DECLARING AND INITIALIZING STRING VARIABLES: Initialization: Example: 1. char str2[3]= Good ; //compile time error - size is smaller than specified value 2. char str3[5]; str3= Good ; we can not separate initialization from declaration. 4. char s1[4]= abc ; char s2[4]; s2=s1; //Error Array name can not be used as the left operand of an assignment operator. 5

TERMINATING NULL CHARACTER The string is a variable-length structure and is stored in a fixed-length array. The array size is not always the size of string and most often it is much larger than the string stored in it. Null character end-of-string 6

READING STRINGS FROM TERMINAL 7

Reading strings from terminal Using scanf function Format specification: %s Example: char name[11]; scanf( %s,name); The problem with the scanf function is that it terminates its input on the first white space it finds. 8

Reading strings from terminal Using scanf function char name[11]; scanf( %s,name); Example: Ajay Patel given as input then scanf takes only Ajay as input because it breaks in blank space (white space). name A j a y \0?????? 9

Reading strings from terminal Using scanf function Example: char adr1[25], adr2[25]; scanf( %s%s,adr1,adr2); 10

Reading strings from terminal Using scanf function Format specification: %ws scanf( %ws,name); Example: char name[10]; scanf( %5s,name); The input string RAM will be stored as: name R A M \0?????? 0 1 2 3 4 5 6 7 8 9 11

Reading strings from terminal Using scanf function Format specification: %ws scanf( %ws,name); Example: char name[10]; scanf( %5s,name); The input string KRISHNA will be stored as: name K R I S H \0???? 0 1 2 3 4 5 6 7 8 9 12

Reading strings from terminal Using a Line of Text Format specification: %[..] also known as edit set conversion code. Example, char line[20]; scanf( %[^\n],line); line A j a y P a t e l \0????????? 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 13

Reading strings from terminal Using getchar and gets function Using getchar() function char ch; ch=getchar(); Example next slide 14

Reading strings from terminal Using getchar and gets function #include<stdio.h> void main() { char line[81],ch; int c=0; printf( Enter text. Press <Return> at end.\n ); do { ch=getchar(); line[c]=ch; c++; }while(ch!= \n ); c=c-1; line[c]= \0 ; } printf( line=%s,line); Output: Enter text. Press <Return> at end. String is interesting chapter. line=string is interesting chapter. 15

Reading strings from terminal Using getchar and gets function Using gets() function Header file stdio.h General format gets(string_variable_name); g e t s ( ) r e a d c h a r a c t e r s i n t o string_variable_name from keyboard until a new-line character is encountered and then appends a null character to the string. 16

Reading strings from terminal Using getchar and gets function Example, char line[81]; gets(line); printf( %s,line); 17

Reading strings from terminal Using getchar and gets function Difference between gets() and scanf() function gets() Format: gets(string_variable_name); It can consider white space until new line character encountered. Example, char ch[10]; gets(ch); scanf() Format: scanf( %ws,name); It can not consider white space while reading a string. Example, char ch[10]; scanf( %s,ch); It is used to read line of text. It is not used to read line of text but word. 18

Writing strings to screen 19

WRITING STRINGS TO SCREEN USING PRINTF() FUNCTION Format specification: %w.p s Here w width and p first p characters of the string. Example char name = Ajay Patel ; printf( %s,name); A j a y P a t e l printf( %10s,name); A j a y P a t e l 20

WRITING STRINGS TO SCREEN USING PRINTF() FUNCTION When the field width is less than size of string, entire string is printed char name = Ajay Patel ; printf( %5s,name); A j a y P a t e l The integer on right side of decimal indicates number of characters to be printed printf( %15.6s,name); printf( %-15.6s,name); A j a y P A j a y P 21

WRITING STRINGS TO SCREEN USING PRINTF() FUNCTION char name = Ajay Patel ; printf( %15.0s,name); 0 characters are to be printed. So nothing is printed on the screen. printf( %.3s,name); A j a printf( %*.*s,w,p,string); printf( %-*.*s,15,6,name); A j a y P 22

23

(Contd.) 24

Writing strings to screen using putchar() and puts() function Using putchar() function: char ch= A ; putchar(ch); Example, char name[5]= Ajay ; i=0; while(name[i]!= \0 ) { putchar(name[i]); i++; } putchar( \n ); A j a y \0 25

Writing strings to screen using putchar() and puts() function Using puts() function: Format: puts(string_variable_name) It prints the string on the screen then move the cursor to the beginning of the next line on the screen. Example, char name[20]; gets(name); puts(name); 26

ARITHMETIC OPERATIONS ON CHARACTERS Whenever a character constant or character v a r i a b l e i s u s e d i n e x p r e s s i o n, i t i s automatically converted into an integer value by the system. The integer value depends on the local character set of the system. If the machine ASCII representation, char x= a ; printf( %d\n,x); output:- 97 Arithmetic operations can be performed on character constant or character variable. x= z -1; 122(ASCII of z) - 1 = 121 27

ARITHMETIC OPERATIONS ON CHARACTERS To check whether the character is upper-case letter or not. ch >= A && ch <= Z We can convert a character digit to its equivalent integer value using the following relationship. x = character 0 // Here x is interger. Example, x= ASCII value of 7 - ASCII value of 0 = 55 48 = 7 28

29

ARITHMETIC OPERATIONS ON CHARACTERS The C library supports a function that converts a string of digits into their integer values. The function takes the form Example, integer_variable = atoi(string); char number[5] = 2013 ; int year; year = atoi(number); atoi() function is stored in the header file stdlib.h. 30

PUTTING STRINGS TOGETHER We can not join two strings together by the simple arithmetic addition. Like, string3 = string1 + string2; string2 = string1 + hello ; are not valid. The characters from string1 and string2 should be copied into the string3 one after the other. The size of array string3 should be large enough to hold the total characters. The process of combining two string together is called concatenation. 31

COMPARISON OF TWO STRINGS Similarly, C does not permit the comparison of two strings directly. Like, if(name1==name2) if(name1== Ajay ) //are invalid It is therefore necessary to compare the two strings to be tested, character by character. 32

33

STRING HANDLING FUNCTIONS Most commonly used string handling functions: Function strcat() strcmp() Action Concatenates two strings Compares two strings strcpy() strlen() Copies one string over another Finds the length of a string 34

STRING HANDLING FUNCTIONS STRCAT() FUNCTION It joins two strings together. It takes the following form: strcat(string1, string2); string2 is appended to string1. Example refer next slide 35

STRING HANDLING FUNCTIONS STRCAT() FUNCTION Example char name[15] = Ajay ; char sname[6] = Patel ; strcat(name,sname); A j a y \0 name sname P a t e l \0 name A j a y P a t e l \0 36

STRING HANDLING FUNCTIONS STRCAT() FUNCTION Example char name[15] = Ajay ; strcat(name, Patel ); name A j a y \0 name A j a y P a t e l \0 37

STRING HANDLING FUNCTIONS STRCAT() FUNCTION Example char name[15]; char fname[6]= Ajay,lname[6]= Patel ; strcat(strcat(name,fname),lname); A j a y \0 fname lname P a t e l \0 name A j a y P a t e l \0 38

STRING HANDLING FUNCTIONS STRCMP() FUNCTION It compares two strings and has a value 0 if they are equal. If they are not, it has numeric difference between the first nonmatching characters in the strings. It takes the following form: strcmp(string1, string2); Example refer next slide 39

STRING HANDLING FUNCTIONS STRCMP() FUNCTION Example strcmp( their, there ); It returns a value -9 (Ascii of (i) - Ascii of (r) ). 40

STRING HANDLING FUNCTIONS STRCMP() FUNCTION Example char name1[15]= Ajay ; char name2[15]= Ajay ; int x; x = strcmp(name1,name2); if(x!= 0) { printf( strings are not equal. ); } else { printf( strings are equal. ); } 41

42

Sorting of strings in alphabetical order

STRING HANDLING FUNCTIONS STRCPY() FUNCTION It copies one string over another. It takes the following form: strcpy(string1, string2); it assigns the contents of string2 to string1. string2 may be a character array variable or a string constant. Example, strcpy(city, AHMEDABAD ); strcpy(city1,city2); size of the array city1 should be large enough to receive the contents of city2. 44

STRING HANDLING FUNCTIONS STRLEN() FUNCTION It counts and returns the number of characters in a string. The general form of strlen is: n = strlen(string); Where n is an integer variable, which receives the value of the length of the string. The argument may be a string constant. The counting ends at the first null character. Example char city[15]= Ahmedabad ; int n=strlen(city); n=9 int x=strlen( Baroda Gujarat ); x=14 45

Other String handling functions strncpy() function The header file string.h contains many more string manipulation functions. It copies only left-most n characters of the source string to the target string variable. strncpy(s1,s2,5); This statement copies the first 5 characters of the source string s2 into the target string s1. Since the first 5 characters may not include the terminating null character, we have to place it explicitly in the 6 th position of s2 as shown below: s1[6]= \0 ; 46

Other String handling functions strncpy() function Example, char str1= Nirma Uni ; char str2= IDS ; strncpy(str1,str2,2); IDrma Uni 47

Other String handling functions strncmp() function The general form is: strncmp(s1,s2,n); this compares the left-most n characters of s1 and s2 and returns 0 if they are equal. Negative number, if s1 sub-string is less than s2 Positive number, otherwise. 48

Other String handling functions strncat() function The general form is: strncat(s1,s2,n); This call will concatenate the left-most n characters of s2 to the end of s1. S1: B A L A \0 S2: G U R U S A M Y \0 After strncat(s1,s2,4); excution: S1: B A L A G U R U \0 49

OTHER STRING HANDLING FUNCTIONS STRSTR() FUNCTION It is a two-parameter function that can be used to locate sub-string in a string. This takes the forms: strstr(s1,s2); strstr(s1, ABC ); The function strstr searches the string s1 to see whether the string s2 is contained in s1. If yes, the function returns the position of the first occurrence of the sub-string. Otherwise, it returns a NULL pointer. 50

OTHER STRING HANDLING FUNCTIONS STRSTR() FUNCTION Example, char s1[15]= Nirma University, s2[10]= Uni ; if(strstr(s1,s2)==null) printf( substring is not found. ); else printf( s2 is as substring of s1. ); 51

OTHER STRING HANDLING FUNCTIONS STRCHR() FUNCTION We also have functions to determine the existence of a character in a string. The function strchr(s1, m ); will locate the first occurrence of the character m. The function strrchr(s1, m ); will locate the last occurrence of the character m in the string s1. 52

TABLE OF STRINGS A list of names can be treated as a table of string and a two-dimensional character array can be used to store the entire list. Example, char student[30][20]; It is used store 30 student names each of length not more than 20 characters. 53

Write a C program to copy one string into another without using string handling function. #include<stdio.h> #include<conio.h> void main() { char str1[50],str2[20]; int i; clrscr(); printf( Enter the string2: ); gets(str2); for(i=0;str2[i]!= \0 ;i++) str1[i]=str2[i]; str1[i]= \0 ; printf( String1 = %s,str1); getch(); } Output: Enter the string2: Nirma University String1 = Nirma University 54

Write a C program to compare two strings without using string handling function. #include<stdio.h> #include<conio.h> void main() { char str1[50],str2[20]; int i; clrscr(); printf( Enter the string1 and string2: ); gets(str1); gets(str2); i=0; while(str1[i]==str2[i] && str1[i]!= \0 && str2[i]!= \0 ) i++; if(str1[i]== \0 && str2[i]== \0 ) printf( Strings are equal. ); else printf( Strings are not equal. ); getch(); } 55

Write a C program that counts the number of words from the given string #include<stdio.h> #include<conio.h> void main() { char str[100]; int count=1,i=0; while(str[i]!='\0') { if(str[i]==' ') { count++; } i++; clrscr(); printf("enter the string:"); gets(str); } printf("\nno. of words in string are: %d",count); getch(); } 56

WRITE A PROGRAM TO PRINT FOLLOWING USING FOR LOOP: 57

#include<stdio.h> #include<string.h> void main() { char str[20]; int i,j; printf("enter the string:"); scanf("%s",str); for(i=0;i<strlen(str);i++) { for(j=0;j<=i;j++) printf("%c",str[j]); printf("\n"); } getch(); } 58

Thank You