SlideShare a Scribd company logo
1 of 41
HANDLING OF CHARACTER
STRINGS
INTRODUCTION
• A string is an array of characters
• Any group of characters defined between double
quotation marks is a constant string
– EXAMPLE: “Man is obviously made to think.”
• To include a double quote in the string to be
printed, use a back slash.
– EXAMPLE: printf(“Well Done !”);
– OUTPUT: Well Done!
– EXAMPLE: printf(“”Well Done!””);
– OUTPUT: “Well Done!”
INTRODUCTION
• Common operations performed on strings are:
– Reading and writing strings
– Combining strings together
– Copying one string to another
– Comparing strings for equality
– Extracting a portion of a string
DECLARING AND INITIALIZING
STRING VARAIBLES
• A string variable is any valid C variable name
and is always declared as an array
– SYNTAX: char string_name[size];
• The size determines the number of characters in
the string-name
– EXAMPLE: char city[10];
• When the compiler assigns a character string to
an character array, it automatically supplies a
null character (‘0’) at the end of the string
• The size should be equal to the maximum
number of characters in the string plus one
DECLARING AND INITIALIZING
STRING VARAIBLES
• Character arrays may be initialized when they
are declared
char city[9] = “NEW YORK”;
char city[9] = (‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’0’);
• When we initialize a character by listing its
elements, we must supply the null terminator
• Can initialize a character array without
specifying the number of elements.
DECLARING AND INITIALIZING
STRING VARAIBLES
• The size of the array will be determined
automatically, based on the number of elements
initialized.
char string[ ] = {'G','O','O','D','0'};
• Can also declare the size much larger than the
string size.
char str[10] = “GOOD”;
• Following will result in a compile time error.
char str[3] = “GOOD”;
DECLARING AND INITIALIZING
STRING VARIABLES
• We cannot separate the initialization from declaration
– char str[5];
– str = “GOOD”;
• Following is not allowed
– char s1[4]=”abc”;
– char s2[4];
– s2 = s1;
• The array name cannot be used as the left operand
of an assignment operator
READING STRING FROM TERMINAL
• Reading words
– The input function scanf can be used with %s format
specification to read in a string of character
char address[15];
scanf(“%s”, address);
– The problem with the scanf function is that it
terminates its input on the first white space it finds
– A white space include blanks, tabs, carriage returns,
form feeds and new lines
INPUT: NEW YORK
– Only the string “NEW” will be read into the array
address
– In the case of character arrays, the ampersand (&) is
not required before the variable name
– The scanf function automatically terminates the string
with a null character
READING STRING FROM TERMINAL
• C supports a format specification known as the
edit set conversion code %[..] that can be used
to read a line containing a variety of characters,
including whitespaces.
– char line[80];
– scanf(“%[^n]”,line);
– printf(“%s”,line);
• Will read a line of input from the keyboard and
display the same on the screen.
READING STRING FROM TERMINAL
• Reading a Line of Text
– We have used getchar function to read a single
character from the terminal
– This getchar function is used repeatedly to read
successive single characters from the input and place
them into a character array
– Thus an entire line of text can be read and stored in
an array
– The reading is terminated when the newline character
(‘n’) is entered and the null character is then inserted
at the end of the string
PROGRAM
#include <stdio.h>
main()
{
char line[100], character;
int c;
c = 0;
printf("Enter Text:n");
do
{
character = getchar();
line[c] = character;
c++;
} while(character != 'n');
c = c-1;
line[c] = '0';
printf("n%sn",line);
}
READING A LINE OF TEXT
• For reading string of text containing whitespaces
is to use the library function gets available in the
<stdio.h>
gets(str)
• It reads characters into str from the keyboard
until a new-line character is encountered and
then appends a null character to the string.
char line[80];
gets(line)
printf(“%s”,line);
• The last two statements may be combined as:
printf(“%s”,gets(line));
READING A LINE OF TEXT
• Does not check array-bounds, so do not input
more characters, it may cause problems
• C does not provide operators that work on
strings directly.
• We cannot assign one string to another directly.
string2 = “ABC”
string1 = string2;
• Are not valid.
• To copy the characters in string2 into sting1, we
may do so on a character-by-character basis.
PROGRAM
#include<stdio.h>
main()
{
char string1[30], string2[30];
int i;
printf("Enter a stringn");
scanf("%s",string2);
for(i=0;string2[i]!='0';i++)
string1[i]=string2[i];
string1[i] = '0';
printf("n");
printf("%sn",string1);
printf("Number of characters = %dn",i);
}
WRITING STRINGS TO SCREEN
• The printf function with %s format is used to print
strings to the screen
• The format %s can be used to display an array
of characters that is terminated by the null
character
printf(“%s”, name);
• This display the entire content of the array name
USING PUTCHAR ANS PUTS
• C supports putchar to output the values of
character variables.
char ch = 'A';
putchar(ch);
• This statement is equivalent to
printf(“%c”,ch);
• Can use this function repeatedly to output string
of characters stored in an array using a loop.
char name[6] = “PARIS”;
for(i=0;i<5;i++)
putchar(name[i]);
putchar(“n”);
USING PUTCHAR ANS PUTS
• To print the string values is to use the function
puts declared in the header file <stdio.h>
puts(str);
• str is a string variable containing a string value.
• This printf the value of the string variable str and
then moves the cursor to the beginning of the
next line on the screen.
char line[80];
gets(line);
puts(line);
• Reads a line of text from the keyboard and
display it on the screen.
ARITHMETIC OPERATIONS ON
CHARACTERS
• C allows to manipulate characters the same way
we do with the numbers
• Whenever a character constant or character
variable is used in an expression, it is
automatically converted into an integer value by
the system
x = ‘a’;
printf(“%dn”,x);
OUTPUT: 97
EXAMPLE: x = ‘z’ – 1;
• The value of z is 122 and the above statement
assign 121 to the variable x
ARITHMETIC OPERATIONS ON
CHARACTERS
• Can use character constants in relational
expressions
EXAMPLE: ch >= ‘A’ && ch <= ‘Z’
• Test whether the character contained in the
variable ch is an upper-case letter
• Can convert a character digit to its equivalent
integer using
x = character – ‘0’;
• Where x is defined as an integer variable and
character contains the character digit
• The character containing the digit ‘7’ then
x = ASCII value of ‘7’ - ASCII value of ‘0’
= 55 – 48 = 7
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
X = atoi(string)
• EXAMPLE:
number = “1998”;
Year = atoi(number);
PUTTING STRINGS TOGETHER
• We cannot assign the string to another directly
• We cannot join two strings together by the
simple arithmetic addition
string3 = strin1 + string2;
string2 = string1 + “hello”;
• The process of combining two strings together is
called concatenation
COMPARISON OF TWO STRINGS
• C does not permit the comparison of two strings
directly
if(name1 == name2)
if(name == “ABC”)
• are not permitted
• It is therefore necessary to compare the two
strings to be tested, character by character
• The comparison is done until a mismatch or one
of the strings terminates into a null character,
whichever occur first
COMPARISON OF TWO STRINGS
i=0;
while(str1[i]==str2[i] && str1[i] != '0' && str2 != '0')
i = i+1;
if(str1[i] == '0' && str2 == '0')
printf("strings are equal");
else
printf("strings are not equal");
Lengths of strings
/* Lengths of strings */
#include <stdio.h>
main()
{
char str1[] = "To be or not to be";
char str2[] = ",that is the question";
int count = 0; /* Stores the string length */
while (str1[count] != '0') /* Increment count till we reach the string */
count++; /* terminating character. */
printf("nThe length of the string1 is", count);
count = 0; /* Reset to zero for next string */
while (str2[count] != '0') /* Count characters in second string */
count++;
printf("nThe length of the string2 is", count);
}
OUTPUT:
The length of the string1 is 18
The length of the string2 is 21
STRING-HANDLING FUNCTIONS
• C library supports large number of string-
handling functions
• Some are
Strings
There are several standard routines that work on string variables.
Some of the string manipulation functions are,
strcpy(string1, string2); - copy string2 into string1
strcat(string1, string2); - concatenate string2 onto the end of string1
strcmp(string1,string2); - 0 if string1 is equals to string2,
< 0 if string1 is less than string2
>0 if string1 is greater than string2
strlen(string); - get the length of a string.
strrev(string); - reverse the string and result is stored in
same string.
strcat() FUNCTION
• The strcat function joins two strings together
– SYNTAX:
strcat(string1, string2);
• string1 and string2 are character array
• string2 is appended to string1
• The null character at the end of the string1 is
removed and string2 is placed from there
• The string2 remains unchanged
Example
#include <stdio.h>
#include <string.h>
int main ()
{
char src[50], dest[50];
puts(“Enter a text1”);
gets(src);
puts(“nEnter a text2”);
gets(dest);
strcat(dest, src);
printf("Final destination string : |%s|", dest);
}
C program to concatenate two strings without using strcat()
#include<stdio.h>
void main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("nEnter First String:");
gets(str1);
printf("nEnter Second String:");
gets(str2);
while(str1[i]!='0')
i++;
while(str2[j]!='0')
{
str1[i]=str2[j];
j++; i++;
}
str1[i]='0';
printf("nConcatenated String is %s",str1);
}
strcmp() FUNCTION
• Compares two strings identified by the arguments and
has a value 0 if they are equal
• If they are not, it has the numeric difference between
the first non-matching characters in the strings
strcmp(string1, string2);
– EXAMPLE:
strcmp(nam1, name2);
strcmp(name1, “John”);
strcmp(“Rom”, “Ram”);
strcmp(“their”, ”there”);
• The above statement will return the value of -9 which
is numeric difference between ASCII “i” and ASCII “r”
is -9
• If the value is negative the string1 is alphabetically
above string2
#include <string.h>
#include<conio.h>
void main(void)
{
char str1[25],str2[25];
int dif,i=0;
clrscr();
printf("nEnter the first String:");
gets(str1);
printf("nEnter the secondString;");
gets(str2);
while(str1[i]!='0'||str2[i]!='0')
{
dif=(str1[i]-str2[i]);
if(dif!=0)
break;
i++;
}
if(dif>0)
printf("%s comes after
%s",str1,str2);
else
{
if(dif<0)
printf("%s comes after
%s",str2,str1);
else
printf("both the strings are same");
}
}
C program to compare two strings using strcmp
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
printf("Enter the first stringn");
gets(a);
printf("Enter the second stringn");
gets(b);
if( strcmp(a,b) == 0 )
printf("Entered strings are equal.n");
else
printf("Entered strings are not equal.n");
}
strcpy() FUNCITON
• Works almost like a string-assignment operator
– SYNTAX:
strcpy(string1, string2);
• Assigns the content of string2 to string1
– EXAMPLE:
strcpy(city, “DELHI”);
• Assign the string “DELHI” to the string variable
city
strcpy(city1, city2);
• Assigns the contents of the string variable city2
to the string variable city1
Copy String Manually without using strcpy()
#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);
for(i=0; s1[i]!='0'; ++i)
{
s2[i]=s1[i];
}
s2[i]='0';
printf("String s2: %s",s2);
}
strlen() FUNCTION
• This function counts and return the number of
characters in a string
– SYNTAX:
n = strlen(string);
• Where n is the integer variable which receives
the value of the length of the string
• The counting ends at the first null character
– EXAMPLE:
Ch = “NEW YORK”;
n = strlen(ch);
printf(String Length = %dn”, n);
– OUTPUT:
String Length = 8
TABLE OF STRINGS
• We use lists of character strings, such as
– List of name of students in a class
– List of name of employees in an organization
– List of places, etc
• These list can be treated as a table of strings and
a two dimensional array can be used to store the
entire list
– EXAMPLE:
student[30][15];
• is an character array which can store a list of 30
names, each of length not more than 15
characters
char city[ ][ ] = { “chandigarh”, “Madrad”, Ahmedab” };
ARRAYS OF STRINGS
• An array of strings is a two-dimensional
array. The row index refers to a particular
string, while the column index refers to a
particular character within a string.
Definition
char identifier[NO_OF_STRINGS][MAX_NO_OF_BYTES_PER_STRING];
Example
char name[5][31];
Initialization
char identifier[NO_OF_STRINGS][MAX_NO_OF_BYTES_PER_STRING] =
{ "initializer 1", "initializer 2", ... };
For example,
char name[5][31] = {“Logesh", "Jean", “ganesh", “moon",
“kumaran”};
Input and Output
Input
To accept input for a list of 5 names, we write
char name[5][31];
for (i = 0; i < 5; i++)
scanf(" %[^n]s", name[i]);
The space in the format string skips leading whitespace before
accepting the string.
Output
char name[5][31] = {"Harry", "Jean", "Jessica", "Irene", "Jim"};
printf("%s", name[2]);
Sorting of string
#include<stdio.h>
int main(){
int i,j,n;
char str[20][20],temp[20];
puts("Enter the no. of string to be sorted");
scanf("%d",&n);
for(i=0;i<=n;i++)
gets(str[i]);
for(i=0;i<=n;i++)
{ for(j=i+1;j<=n;j++){
{ if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
printf("The sorted stringn");
for(i=0;i<=n;i++)
puts(str[i]);
}
Search a name in a give list
#include<stdio.h> #include<string.h>
int main()
{
char name[5][10],found[10];
int j,i,flag=0;
printf("Enter a name :");
for(i=0;i<5;i++)
scanf("%s",name[i]);
printf("enter a searching stringn");
scanf("%s",found);
for(i=0;i<5;i++)
{
if(strcmp(name[i],found)==0)
{ flag=1; break; }
}
if(flag==1)
printf("String foundn");
else
printf("nString not found");
}

More Related Content

What's hot (20)

String c
String cString c
String c
 
String in c programming
String in c programmingString in c programming
String in c programming
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Function in c
Function in cFunction in c
Function in c
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Java strings
Java   stringsJava   strings
Java strings
 
Unit 8. Pointers
Unit 8. PointersUnit 8. Pointers
Unit 8. Pointers
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Unit 2. Elements of C
Unit 2. Elements of CUnit 2. Elements of C
Unit 2. Elements of C
 
Implementation Of String Functions In C
Implementation Of String Functions In CImplementation Of String Functions In C
Implementation Of String Functions In C
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Looping in C
Looping in CLooping in C
Looping in C
 
Keywords in c language
Keywords in c languageKeywords in c language
Keywords in c language
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Strings in C
Strings in CStrings in C
Strings in C
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C Programming
 

Viewers also liked

BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015Appili Vamsi Krishna
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Appili Vamsi Krishna
 
C language for Semester Exams for Engineers
C language for Semester Exams for Engineers C language for Semester Exams for Engineers
C language for Semester Exams for Engineers Appili Vamsi Krishna
 
Difference between structure and union
Difference between structure and unionDifference between structure and union
Difference between structure and unionAppili Vamsi Krishna
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing TechniquesAppili Vamsi Krishna
 
Types of storage class specifiers in c programming
Types of storage class specifiers in c programmingTypes of storage class specifiers in c programming
Types of storage class specifiers in c programmingAppili Vamsi Krishna
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmigAppili Vamsi Krishna
 
Planers machine
Planers machinePlaners machine
Planers machineBilalwahla
 
Conventional machining vs. non conventional machining
Conventional machining vs. non conventional machiningConventional machining vs. non conventional machining
Conventional machining vs. non conventional machiningonlinemetallurgy.com
 

Viewers also liked (11)

BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015
 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
C language for Semester Exams for Engineers
C language for Semester Exams for Engineers C language for Semester Exams for Engineers
C language for Semester Exams for Engineers
 
Difference between structure and union
Difference between structure and unionDifference between structure and union
Difference between structure and union
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing Techniques
 
Types of storage class specifiers in c programming
Types of storage class specifiers in c programmingTypes of storage class specifiers in c programming
Types of storage class specifiers in c programming
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Planers machine
Planers machinePlaners machine
Planers machine
 
Conventional machining vs. non conventional machining
Conventional machining vs. non conventional machiningConventional machining vs. non conventional machining
Conventional machining vs. non conventional machining
 

Similar to Handling of character strings C programming

Similar to Handling of character strings C programming (20)

Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
Operation on string presentation
Operation on string presentationOperation on string presentation
Operation on string presentation
 
String notes
String notesString notes
String notes
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
 
Lecture 05 2017
Lecture 05 2017Lecture 05 2017
Lecture 05 2017
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
Ch09
Ch09Ch09
Ch09
 
Array &strings
Array &stringsArray &strings
Array &strings
 
Strings
StringsStrings
Strings
 
Team 1
Team 1Team 1
Team 1
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
String in programming language in c or c++
String in programming language in c or c++String in programming language in c or c++
String in programming language in c or c++
 
Strings in c
Strings in cStrings in c
Strings in c
 
C string
C stringC string
C string
 

Recently uploaded

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 

Recently uploaded (20)

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 

Handling of character strings C programming

  • 2. INTRODUCTION • A string is an array of characters • Any group of characters defined between double quotation marks is a constant string – EXAMPLE: “Man is obviously made to think.” • To include a double quote in the string to be printed, use a back slash. – EXAMPLE: printf(“Well Done !”); – OUTPUT: Well Done! – EXAMPLE: printf(“”Well Done!””); – OUTPUT: “Well Done!”
  • 3. INTRODUCTION • Common operations performed on strings are: – Reading and writing strings – Combining strings together – Copying one string to another – Comparing strings for equality – Extracting a portion of a string
  • 4. DECLARING AND INITIALIZING STRING VARAIBLES • A string variable is any valid C variable name and is always declared as an array – SYNTAX: char string_name[size]; • The size determines the number of characters in the string-name – EXAMPLE: char city[10]; • When the compiler assigns a character string to an character array, it automatically supplies a null character (‘0’) at the end of the string • The size should be equal to the maximum number of characters in the string plus one
  • 5. DECLARING AND INITIALIZING STRING VARAIBLES • Character arrays may be initialized when they are declared char city[9] = “NEW YORK”; char city[9] = (‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’0’); • When we initialize a character by listing its elements, we must supply the null terminator • Can initialize a character array without specifying the number of elements.
  • 6. DECLARING AND INITIALIZING STRING VARAIBLES • The size of the array will be determined automatically, based on the number of elements initialized. char string[ ] = {'G','O','O','D','0'}; • Can also declare the size much larger than the string size. char str[10] = “GOOD”; • Following will result in a compile time error. char str[3] = “GOOD”;
  • 7. DECLARING AND INITIALIZING STRING VARIABLES • We cannot separate the initialization from declaration – char str[5]; – str = “GOOD”; • Following is not allowed – char s1[4]=”abc”; – char s2[4]; – s2 = s1; • The array name cannot be used as the left operand of an assignment operator
  • 8. READING STRING FROM TERMINAL • Reading words – The input function scanf can be used with %s format specification to read in a string of character char address[15]; scanf(“%s”, address); – The problem with the scanf function is that it terminates its input on the first white space it finds – A white space include blanks, tabs, carriage returns, form feeds and new lines INPUT: NEW YORK – Only the string “NEW” will be read into the array address – In the case of character arrays, the ampersand (&) is not required before the variable name – The scanf function automatically terminates the string with a null character
  • 9. READING STRING FROM TERMINAL • C supports a format specification known as the edit set conversion code %[..] that can be used to read a line containing a variety of characters, including whitespaces. – char line[80]; – scanf(“%[^n]”,line); – printf(“%s”,line); • Will read a line of input from the keyboard and display the same on the screen.
  • 10. READING STRING FROM TERMINAL • Reading a Line of Text – We have used getchar function to read a single character from the terminal – This getchar function is used repeatedly to read successive single characters from the input and place them into a character array – Thus an entire line of text can be read and stored in an array – The reading is terminated when the newline character (‘n’) is entered and the null character is then inserted at the end of the string
  • 11. PROGRAM #include <stdio.h> main() { char line[100], character; int c; c = 0; printf("Enter Text:n"); do { character = getchar(); line[c] = character; c++; } while(character != 'n'); c = c-1; line[c] = '0'; printf("n%sn",line); }
  • 12. READING A LINE OF TEXT • For reading string of text containing whitespaces is to use the library function gets available in the <stdio.h> gets(str) • It reads characters into str from the keyboard until a new-line character is encountered and then appends a null character to the string. char line[80]; gets(line) printf(“%s”,line); • The last two statements may be combined as: printf(“%s”,gets(line));
  • 13. READING A LINE OF TEXT • Does not check array-bounds, so do not input more characters, it may cause problems • C does not provide operators that work on strings directly. • We cannot assign one string to another directly. string2 = “ABC” string1 = string2; • Are not valid. • To copy the characters in string2 into sting1, we may do so on a character-by-character basis.
  • 14. PROGRAM #include<stdio.h> main() { char string1[30], string2[30]; int i; printf("Enter a stringn"); scanf("%s",string2); for(i=0;string2[i]!='0';i++) string1[i]=string2[i]; string1[i] = '0'; printf("n"); printf("%sn",string1); printf("Number of characters = %dn",i); }
  • 15. WRITING STRINGS TO SCREEN • The printf function with %s format is used to print strings to the screen • The format %s can be used to display an array of characters that is terminated by the null character printf(“%s”, name); • This display the entire content of the array name
  • 16. USING PUTCHAR ANS PUTS • C supports putchar to output the values of character variables. char ch = 'A'; putchar(ch); • This statement is equivalent to printf(“%c”,ch); • Can use this function repeatedly to output string of characters stored in an array using a loop. char name[6] = “PARIS”; for(i=0;i<5;i++) putchar(name[i]); putchar(“n”);
  • 17. USING PUTCHAR ANS PUTS • To print the string values is to use the function puts declared in the header file <stdio.h> puts(str); • str is a string variable containing a string value. • This printf the value of the string variable str and then moves the cursor to the beginning of the next line on the screen. char line[80]; gets(line); puts(line); • Reads a line of text from the keyboard and display it on the screen.
  • 18. ARITHMETIC OPERATIONS ON CHARACTERS • C allows to manipulate characters the same way we do with the numbers • Whenever a character constant or character variable is used in an expression, it is automatically converted into an integer value by the system x = ‘a’; printf(“%dn”,x); OUTPUT: 97 EXAMPLE: x = ‘z’ – 1; • The value of z is 122 and the above statement assign 121 to the variable x
  • 19. ARITHMETIC OPERATIONS ON CHARACTERS • Can use character constants in relational expressions EXAMPLE: ch >= ‘A’ && ch <= ‘Z’ • Test whether the character contained in the variable ch is an upper-case letter • Can convert a character digit to its equivalent integer using x = character – ‘0’; • Where x is defined as an integer variable and character contains the character digit • The character containing the digit ‘7’ then x = ASCII value of ‘7’ - ASCII value of ‘0’ = 55 – 48 = 7
  • 20. 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 X = atoi(string) • EXAMPLE: number = “1998”; Year = atoi(number);
  • 21. PUTTING STRINGS TOGETHER • We cannot assign the string to another directly • We cannot join two strings together by the simple arithmetic addition string3 = strin1 + string2; string2 = string1 + “hello”; • The process of combining two strings together is called concatenation
  • 22. COMPARISON OF TWO STRINGS • C does not permit the comparison of two strings directly if(name1 == name2) if(name == “ABC”) • are not permitted • It is therefore necessary to compare the two strings to be tested, character by character • The comparison is done until a mismatch or one of the strings terminates into a null character, whichever occur first
  • 23. COMPARISON OF TWO STRINGS i=0; while(str1[i]==str2[i] && str1[i] != '0' && str2 != '0') i = i+1; if(str1[i] == '0' && str2 == '0') printf("strings are equal"); else printf("strings are not equal");
  • 24. Lengths of strings /* Lengths of strings */ #include <stdio.h> main() { char str1[] = "To be or not to be"; char str2[] = ",that is the question"; int count = 0; /* Stores the string length */ while (str1[count] != '0') /* Increment count till we reach the string */ count++; /* terminating character. */ printf("nThe length of the string1 is", count); count = 0; /* Reset to zero for next string */ while (str2[count] != '0') /* Count characters in second string */ count++; printf("nThe length of the string2 is", count); } OUTPUT: The length of the string1 is 18 The length of the string2 is 21
  • 25. STRING-HANDLING FUNCTIONS • C library supports large number of string- handling functions • Some are
  • 26. Strings There are several standard routines that work on string variables. Some of the string manipulation functions are, strcpy(string1, string2); - copy string2 into string1 strcat(string1, string2); - concatenate string2 onto the end of string1 strcmp(string1,string2); - 0 if string1 is equals to string2, < 0 if string1 is less than string2 >0 if string1 is greater than string2 strlen(string); - get the length of a string. strrev(string); - reverse the string and result is stored in same string.
  • 27. strcat() FUNCTION • The strcat function joins two strings together – SYNTAX: strcat(string1, string2); • string1 and string2 are character array • string2 is appended to string1 • The null character at the end of the string1 is removed and string2 is placed from there • The string2 remains unchanged
  • 28. Example #include <stdio.h> #include <string.h> int main () { char src[50], dest[50]; puts(“Enter a text1”); gets(src); puts(“nEnter a text2”); gets(dest); strcat(dest, src); printf("Final destination string : |%s|", dest); }
  • 29. C program to concatenate two strings without using strcat() #include<stdio.h> void main(void) { char str1[25],str2[25]; int i=0,j=0; printf("nEnter First String:"); gets(str1); printf("nEnter Second String:"); gets(str2); while(str1[i]!='0') i++; while(str2[j]!='0') { str1[i]=str2[j]; j++; i++; } str1[i]='0'; printf("nConcatenated String is %s",str1); }
  • 30. strcmp() FUNCTION • Compares two strings identified by the arguments and has a value 0 if they are equal • If they are not, it has the numeric difference between the first non-matching characters in the strings strcmp(string1, string2); – EXAMPLE: strcmp(nam1, name2); strcmp(name1, “John”); strcmp(“Rom”, “Ram”); strcmp(“their”, ”there”); • The above statement will return the value of -9 which is numeric difference between ASCII “i” and ASCII “r” is -9 • If the value is negative the string1 is alphabetically above string2
  • 31. #include <string.h> #include<conio.h> void main(void) { char str1[25],str2[25]; int dif,i=0; clrscr(); printf("nEnter the first String:"); gets(str1); printf("nEnter the secondString;"); gets(str2); while(str1[i]!='0'||str2[i]!='0') { dif=(str1[i]-str2[i]); if(dif!=0) break; i++; } if(dif>0) printf("%s comes after %s",str1,str2); else { if(dif<0) printf("%s comes after %s",str2,str1); else printf("both the strings are same"); } }
  • 32. C program to compare two strings using strcmp #include <stdio.h> #include <string.h> int main() { char a[100], b[100]; printf("Enter the first stringn"); gets(a); printf("Enter the second stringn"); gets(b); if( strcmp(a,b) == 0 ) printf("Entered strings are equal.n"); else printf("Entered strings are not equal.n"); }
  • 33. strcpy() FUNCITON • Works almost like a string-assignment operator – SYNTAX: strcpy(string1, string2); • Assigns the content of string2 to string1 – EXAMPLE: strcpy(city, “DELHI”); • Assign the string “DELHI” to the string variable city strcpy(city1, city2); • Assigns the contents of the string variable city2 to the string variable city1
  • 34. Copy String Manually without using strcpy() #include <stdio.h> int main() { char s1[100], s2[100], i; printf("Enter string s1: "); scanf("%s",s1); for(i=0; s1[i]!='0'; ++i) { s2[i]=s1[i]; } s2[i]='0'; printf("String s2: %s",s2); }
  • 35. strlen() FUNCTION • This function counts and return the number of characters in a string – SYNTAX: n = strlen(string); • Where n is the integer variable which receives the value of the length of the string • The counting ends at the first null character – EXAMPLE: Ch = “NEW YORK”; n = strlen(ch); printf(String Length = %dn”, n); – OUTPUT: String Length = 8
  • 36. TABLE OF STRINGS • We use lists of character strings, such as – List of name of students in a class – List of name of employees in an organization – List of places, etc • These list can be treated as a table of strings and a two dimensional array can be used to store the entire list – EXAMPLE: student[30][15]; • is an character array which can store a list of 30 names, each of length not more than 15 characters char city[ ][ ] = { “chandigarh”, “Madrad”, Ahmedab” };
  • 37. ARRAYS OF STRINGS • An array of strings is a two-dimensional array. The row index refers to a particular string, while the column index refers to a particular character within a string. Definition char identifier[NO_OF_STRINGS][MAX_NO_OF_BYTES_PER_STRING]; Example char name[5][31];
  • 38. Initialization char identifier[NO_OF_STRINGS][MAX_NO_OF_BYTES_PER_STRING] = { "initializer 1", "initializer 2", ... }; For example, char name[5][31] = {“Logesh", "Jean", “ganesh", “moon", “kumaran”};
  • 39. Input and Output Input To accept input for a list of 5 names, we write char name[5][31]; for (i = 0; i < 5; i++) scanf(" %[^n]s", name[i]); The space in the format string skips leading whitespace before accepting the string. Output char name[5][31] = {"Harry", "Jean", "Jessica", "Irene", "Jim"}; printf("%s", name[2]);
  • 40. Sorting of string #include<stdio.h> int main(){ int i,j,n; char str[20][20],temp[20]; puts("Enter the no. of string to be sorted"); scanf("%d",&n); for(i=0;i<=n;i++) gets(str[i]); for(i=0;i<=n;i++) { for(j=i+1;j<=n;j++){ { if(strcmp(str[i],str[j])>0) { strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); } } } printf("The sorted stringn"); for(i=0;i<=n;i++) puts(str[i]); }
  • 41. Search a name in a give list #include<stdio.h> #include<string.h> int main() { char name[5][10],found[10]; int j,i,flag=0; printf("Enter a name :"); for(i=0;i<5;i++) scanf("%s",name[i]); printf("enter a searching stringn"); scanf("%s",found); for(i=0;i<5;i++) { if(strcmp(name[i],found)==0) { flag=1; break; } } if(flag==1) printf("String foundn"); else printf("nString not found"); }