Chapter 8 “Character Arrays and Strings” Prepared by: Prof. Ajay M. Patel CE, IDS, NU.

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.
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.
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.
Chapter 10.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
To remind us We finished the last day by introducing If statements Their structure was:::::::::
PRESENTED BY: ER. SUMANPREET KAUR LECTURER IN CE DEPTT. GPCG ASR.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
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.
Chapter 5: Data Input and Output Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
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.
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.
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’};
Chapter 8: Character and String CMPD144: Programming 1.
Chapter-4 Managing input and Output operation.  Reading, processing and writing of data are three essential functions of a computer program.  Most programs.
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:
© Oxford University Press All rights reserved. CHAPTER 6 STRINGS.
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.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Characters and Strings Functions.
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
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.
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.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
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.
Chapter 2 Array and String. Array Definition of Array : An array is a sequence or collection of the related data items that share a common name. Purpose.
C Characters and Strings
Strings CSCI 112: Programming in C.
INC 161 , CPE 100 Computer Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
C Characters and Strings
Fundamentals of Characters and Strings
Lecture 8 String 1. Concept of strings String and pointers
Chapter 7 Text Input/Output Objectives
A First Book of ANSI C Fourth Edition
CSE 303 Lecture 14 Strings in C
Module 2 Arrays and strings – example programs.
Strings A string is a sequence of characters treated as a group
Arrays in C.
Chapter 8 - Characters and Strings
CS111 Computer Programming
Lecture 8b: Strings BJ Furman 15OCT2012.
C Stuff CS 2308.
INC 161 , CPE 100 Computer Programming
Pointers and Pointer-Based Strings
Strings Dr. Soha S. Zaghloul updated by Rasha ALEidan
Chapter 2 Array and String Visit to more Learning Resources.
Strings What is a string? It is an array of characters terminated with
Chapter 8 Character Arrays and Strings
CPS120: Introduction to Computer Science
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Strings in C Array of characters is called a string.
Strings #include <stdio.h>
Characters and Strings Functions
Strings Adapted from Dr. Mary Eberlein, UT Austin.
C Characters and Strings
Introduction to Problem Solving and Programming
Presentation transcript:

Chapter 8 “Character Arrays and Strings” Prepared by: Prof. Ajay M. Patel CE, IDS, NU

Introduction 2 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 !”

Declaring and initializing string variables: 3 C does not support strings as a data type. Strings are represent 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’)

Declaring and initializing string variables: 4 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 determine from list of values. 4. char str[10] = “Good”; str Good\0

Declaring and initializing string variables: 5 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.

Terminating Null Character 6 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

Reading strings from terminal 7

Reading strings from terminal  Using scanf function 8 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.

Reading strings from terminal  Using scanf function 9 char name[11]; scanf(“%s”,name); Example: Ajay Patel given as input than scanf takes only Ajay as input because blank space (it is white space) is their in it. name Ajay\0??????

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

Reading strings from terminal  Using scanf function 11 Format specification: %ws scanf(“%ws”,name); Example: char name[10]; scanf(“%5s”,name); The input string RAM will be stored as: name RAM\0??????

Reading strings from terminal  Using scanf function 12 Format specification: %ws scanf(“%ws”,name); Example: char name[10]; scanf(“%5s”,name); The input string KRISHNA will be stored as: name KRISH\0????

Reading strings from terminal  Using a Line of Text 13 Format specification: %[..]  also known as edit set conversion code. Example, Char line[20]; scanf(“%[^\n]”,line); line AjayPatel \0?????????

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

Reading strings from terminal  Using getchar and gets function 15 #include void main() { char line[81],ch; int c=0; printf(“Enter text. Press 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 texr. Press at end. String is interesting chapter. line=String is interesting chapter.

Reading strings from terminal  Using getchar and gets function 16 Using gets() function Header file  stdio.h General format gets(string_variable_name); gets() read characters into string_variable_name from keyboard until a new-line character is encountered and then appends a null character to the string.

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

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

Writing strings to screen 19

Writing strings to screen  using printf() function 20 Format specification: %w.p s Here w – width and p – first p characters of the string. Example char name = “Ajay Patel”; printf(“%s”,name); printf(“%10s”,name); AjayPatel AjayPatel

Writing strings to screen  using printf() function 21 char name = “Ajay Patel”; printf(“%5s”,name); printf(“%15.6s”,name); printf(“%-15.6s”,name); AjayPatel AjayP AjayP

Writing strings to screen  using printf() function 22 char name = “Ajay Patel”; printf(“%15.0s”,name); 0 characters are printed. So nothing is printed on the screen. printf(“%.3s”,name); printf(“%*.*s”,w,p,string); printf(“%-*.*s”,15,6,name); Aja AjayP

Writing strings to screen  using putchar() and puts() function 23 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’); Ajay\0

Writing strings to screen  using putchar() and puts() function 24 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);

Arithmetic operations on characters 25 Whenever a character constant or character variable is used in expression, it is 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 perform on character constant or character variable. x=‘z’-1;  122(ASCII of z) - 1 = 121

Arithmetic operations on characters 26 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

Arithmetic operations on characters 27 The C library supports a function that converts a string of digits into their integer values. The function takes the form integer_variable = atoi(string); Example, char number[5] = “2013”; int year; year = atoi(number); atoi() function is stored in the header file stdlib.h.

Putting strings together 28 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.

Comparison of two strings 29 Once again, 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.

String handling functions 30 Most commonly used string handling functions: FunctionAction strcat()Concatenates two strings strcmp()Compares two strings strcpy()Copies one string over another strlen()Finds the length if a string

String handling functions  strcat() function 31 It joins two strings together. It takes the following form: strcat(string1, string2); string2 is appended to string1. Example refer next slide

String handling functions  strcat() function 32 Example char name[15] = “Ajay ”; char sname[6] = “Patel”; strcat(name,sname); name Ajay\0 sname Patel \0 name AjayPatel \0

String handling functions  strcat() function 33 Example char name[15] = “Ajay ”; strcat(name,”Patel”); name Ajay\0 name AjayPatel \0

String handling functions  strcat() function 34 Example char name[15]; char fname[6]=“Ajay ”,lname[6]=“Patel”; strcat(strcat(name,fname),lname); fname Ajay\0 name AjayPatel \0 lname Patel \0

String handling functions  strcmp() function 35 It compares two strings and has a value 0 if they are equal. If they are not, it has numeric difference between the first non- matching characters in the strings. It takes the following form: strcmp(string1, string2); Example refer next slide

String handling functions  strcmp() function 36 Example strcmp(“their”,”there”); It returns a value -9 (Ascii of (i) - Ascii of (r) ).

String handling functions  strcmp() function 37 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. ”); }

String handling functions  strcpy() function 38 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.

String handling functions  strlen() function 39 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

Other String handling functions  strncpy() function 40 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’;

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

Other String handling functions  strncmp() function 42 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.

Other String handling functions  strncat() function 43 The general form is: strncmp(s1,s2,n); This call will concatenate the left-most n characters of s2 to the end of s1. After strncat(s1,s2,4); excution: S1:BALA\0 S2:GURUSAMY\0 S1:BALAGURU\0

Other String handling functions  strstr() function 44 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.

Other String handling functions  strstr() function 45 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.”);

Other String handling functions  strchr() function 46 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.

Table of strings 47 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.

Write a C program to copy one string into another without using string handling function. 48 #include 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

Write a C program to compare two strings without using string handling function. 49 #include 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(); }

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

Write a program to print following using for loop: 51

52 #include void main() { char str[20]; int i,j; clrscr(); 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(); }

Thank You