SlideShare a Scribd company logo
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)

Function in c
Function in cFunction in c
Function in c
savitamhaske
 
Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
Tanmay Modi
 
String in c programming
String in c programmingString in c programming
String in c programming
Devan Thakur
 
Strings in C
Strings in CStrings in C
Strings in C
Kamal Acharya
 
File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
Samiksha Pun
 
Structure in c
Structure in cStructure in c
Structure in c
Prabhu Govind
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
AbhayDhupar
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
Kamal Acharya
 
Presentation on array
Presentation on array Presentation on array
Presentation on array
topu93
 
Array data structure
Array data structureArray data structure
Array data structure
maamir farooq
 
Arrays in c
Arrays in cArrays in c
Arrays in c
vampugani
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
Ashim Lamichhane
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
Functions in c
Functions in cFunctions in c
Functions in c
sunila tharagaturi
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
programming9
 
Arrays in c
Arrays in cArrays in c
Arrays in c
CHANDAN KUMAR
 
Arrays in c
Arrays in cArrays in c
Arrays in c
Jeeva Nanthini
 
C Programming : Arrays
C Programming : ArraysC Programming : Arrays
C Programming : Arrays
Gagan Deep
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 
Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
Tanmay Modi
 
String in c programming
String in c programmingString in c programming
String in c programming
Devan Thakur
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
Samiksha Pun
 
Structure in c
Structure in cStructure in c
Structure in c
Prabhu Govind
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
AbhayDhupar
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
Kamal Acharya
 
Presentation on array
Presentation on array Presentation on array
Presentation on array
topu93
 
Array data structure
Array data structureArray data structure
Array data structure
maamir farooq
 
Arrays in c
Arrays in cArrays in c
Arrays in c
vampugani
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
Ashim Lamichhane
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
programming9
 
C Programming : Arrays
C Programming : ArraysC Programming : Arrays
C Programming : Arrays
Gagan Deep
 

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
Appili Vamsi Krishna
 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming
Appili 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 union
Appili Vamsi Krishna
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing Techniques
Appili 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 programming
Appili Vamsi Krishna
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
Appili Vamsi Krishna
 
Planers machine
Planers machinePlaners machine
Planers machine
Bilalwahla
 
Conventional machining vs. non conventional machining
Conventional machining vs. non conventional machiningConventional machining vs. non conventional machining
Conventional machining vs. non conventional machining
onlinemetallurgy.com
 
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
Appili Vamsi Krishna
 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming
Appili 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 union
Appili Vamsi Krishna
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing Techniques
Appili 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 programming
Appili Vamsi Krishna
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
Appili Vamsi Krishna
 
Planers machine
Planers machinePlaners machine
Planers machine
Bilalwahla
 
Conventional machining vs. non conventional machining
Conventional machining vs. non conventional machiningConventional machining vs. non conventional machining
Conventional machining vs. non conventional machining
onlinemetallurgy.com
 
Ad

Similar to Handling of character strings C programming (20)

Lecture 05 2017
Lecture 05 2017Lecture 05 2017
Lecture 05 2017
Jesmin Akhter
 
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
SowmyaJyothi3
 
[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++
Muhammad Hammad Waseem
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
Sowmya Jyothi
 
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPTCfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
Chapterabcdefghijklmnopqrdstuvwxydanniipo
ChapterabcdefghijklmnopqrdstuvwxydanniipoChapterabcdefghijklmnopqrdstuvwxydanniipo
Chapterabcdefghijklmnopqrdstuvwxydanniipo
abritip
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
웅식 전
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
yndaravind
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
Hemantha Kulathilake
 
14 strings
14 strings14 strings
14 strings
Rohit Shrivastava
 
Computer Programming Utilities the subject of BE first year students, and thi...
Computer Programming Utilities the subject of BE first year students, and thi...Computer Programming Utilities the subject of BE first year students, and thi...
Computer Programming Utilities the subject of BE first year students, and thi...
jr2710
 
pps unit 3.pptx
pps unit 3.pptxpps unit 3.pptx
pps unit 3.pptx
mathesh0303
 
Mcai pic u 4 function, storage class and array and strings
Mcai pic u 4 function, storage class and array and stringsMcai pic u 4 function, storage class and array and strings
Mcai pic u 4 function, storage class and array and strings
Rai University
 
Week6_P_String.pptx
Week6_P_String.pptxWeek6_P_String.pptx
Week6_P_String.pptx
OluwafolakeOjo
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
Rai University
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and strings
Rai University
 
Btech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and stringsBtech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and strings
Rai University
 
Functions torage class and array and strings-
Functions torage class and array and strings-Functions torage class and array and strings-
Functions torage class and array and strings-
aneebkmct
 
Bsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and stringsBsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and strings
Rai University
 
Lecture 05 2017
Lecture 05 2017Lecture 05 2017
Lecture 05 2017
Jesmin Akhter
 
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
SowmyaJyothi3
 
[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++
Muhammad Hammad Waseem
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
Sowmya Jyothi
 
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPTCfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
Chapterabcdefghijklmnopqrdstuvwxydanniipo
ChapterabcdefghijklmnopqrdstuvwxydanniipoChapterabcdefghijklmnopqrdstuvwxydanniipo
Chapterabcdefghijklmnopqrdstuvwxydanniipo
abritip
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
yndaravind
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
Hemantha Kulathilake
 
Computer Programming Utilities the subject of BE first year students, and thi...
Computer Programming Utilities the subject of BE first year students, and thi...Computer Programming Utilities the subject of BE first year students, and thi...
Computer Programming Utilities the subject of BE first year students, and thi...
jr2710
 
pps unit 3.pptx
pps unit 3.pptxpps unit 3.pptx
pps unit 3.pptx
mathesh0303
 
Mcai pic u 4 function, storage class and array and strings
Mcai pic u 4 function, storage class and array and stringsMcai pic u 4 function, storage class and array and strings
Mcai pic u 4 function, storage class and array and strings
Rai University
 
Week6_P_String.pptx
Week6_P_String.pptxWeek6_P_String.pptx
Week6_P_String.pptx
OluwafolakeOjo
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
Rai University
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and strings
Rai University
 
Btech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and stringsBtech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and strings
Rai University
 
Functions torage class and array and strings-
Functions torage class and array and strings-Functions torage class and array and strings-
Functions torage class and array and strings-
aneebkmct
 
Bsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and stringsBsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and strings
Rai University
 
Ad

Recently uploaded (20)

Uterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managmentUterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managment
Ritu480198
 
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGYHUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
DHARMENDRA SAHU
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
Critical Thinking and Bias with Jibi Moses
Critical Thinking and Bias with Jibi MosesCritical Thinking and Bias with Jibi Moses
Critical Thinking and Bias with Jibi Moses
Excellence Foundation for South Sudan
 
How to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo SlidesHow to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo Slides
Celine George
 
Exploring Identity Through Colombian Companies
Exploring Identity Through Colombian CompaniesExploring Identity Through Colombian Companies
Exploring Identity Through Colombian Companies
OlgaLeonorTorresSnch
 
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ..."Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
Arshad Shaikh
 
A Brief Introduction About Jack Lutkus
A Brief Introduction About  Jack  LutkusA Brief Introduction About  Jack  Lutkus
A Brief Introduction About Jack Lutkus
Jack Lutkus
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo SlidesHow to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
Celine George
 
How to Setup Lunch in Odoo 18 - Odoo guides
How to Setup Lunch in Odoo 18 - Odoo guidesHow to Setup Lunch in Odoo 18 - Odoo guides
How to Setup Lunch in Odoo 18 - Odoo guides
Celine George
 
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly WorkshopsLDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDM & Mia eStudios
 
Multicultural approach in education - B.Ed
Multicultural approach in education - B.EdMulticultural approach in education - B.Ed
Multicultural approach in education - B.Ed
prathimagowda443
 
Order Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptxOrder Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptx
Arshad Shaikh
 
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATIONTHE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
PROF. PAUL ALLIEU KAMARA
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
LETÂŽS PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LETÂŽS PRACTICE GRAMMAR USING SIMPLE PAST TENSELETÂŽS PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LETÂŽS PRACTICE GRAMMAR USING SIMPLE PAST TENSE
OlgaLeonorTorresSnch
 
Odoo 18 Point of Sale PWA - Odoo Slides
Odoo 18 Point of Sale PWA  - Odoo  SlidesOdoo 18 Point of Sale PWA  - Odoo  Slides
Odoo 18 Point of Sale PWA - Odoo Slides
Celine George
 
LDMMIA About me 2025 Edition 3 College Volume
LDMMIA About me 2025 Edition 3 College VolumeLDMMIA About me 2025 Edition 3 College Volume
LDMMIA About me 2025 Edition 3 College Volume
LDM & Mia eStudios
 
Uterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managmentUterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managment
Ritu480198
 
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGYHUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
DHARMENDRA SAHU
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
How to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo SlidesHow to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo Slides
Celine George
 
Exploring Identity Through Colombian Companies
Exploring Identity Through Colombian CompaniesExploring Identity Through Colombian Companies
Exploring Identity Through Colombian Companies
OlgaLeonorTorresSnch
 
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ..."Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
Arshad Shaikh
 
A Brief Introduction About Jack Lutkus
A Brief Introduction About  Jack  LutkusA Brief Introduction About  Jack  Lutkus
A Brief Introduction About Jack Lutkus
Jack Lutkus
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo SlidesHow to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
Celine George
 
How to Setup Lunch in Odoo 18 - Odoo guides
How to Setup Lunch in Odoo 18 - Odoo guidesHow to Setup Lunch in Odoo 18 - Odoo guides
How to Setup Lunch in Odoo 18 - Odoo guides
Celine George
 
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly WorkshopsLDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDM & Mia eStudios
 
Multicultural approach in education - B.Ed
Multicultural approach in education - B.EdMulticultural approach in education - B.Ed
Multicultural approach in education - B.Ed
prathimagowda443
 
Order Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptxOrder Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptx
Arshad Shaikh
 
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATIONTHE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
PROF. PAUL ALLIEU KAMARA
 
LETÂŽS PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LETÂŽS PRACTICE GRAMMAR USING SIMPLE PAST TENSELETÂŽS PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LETÂŽS PRACTICE GRAMMAR USING SIMPLE PAST TENSE
OlgaLeonorTorresSnch
 
Odoo 18 Point of Sale PWA - Odoo Slides
Odoo 18 Point of Sale PWA  - Odoo  SlidesOdoo 18 Point of Sale PWA  - Odoo  Slides
Odoo 18 Point of Sale PWA - Odoo Slides
Celine George
 
LDMMIA About me 2025 Edition 3 College Volume
LDMMIA About me 2025 Edition 3 College VolumeLDMMIA About me 2025 Edition 3 College Volume
LDMMIA About me 2025 Edition 3 College Volume
LDM & Mia eStudios
 

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"); }