Strings Final
Strings Final
Agenda
• Introduction
char name[20];
char address[25];
char city[15];
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”;
• Eg:- char name[ 8] = {‘P’, ‘R’, ‘O’, ‘G’, ‘R’, ‘A’, ‘M’, '\0’};
P R O G R A M \0
• 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.
EXAMPLE PROGRAM
#include<stdio.h>
int main () OUTPUT:
{
char Hello
greeting[
6] = {'H',
'e', 'l', 'l',
'o', '\0’};
//OR
// char
greeting[]
= “Hello”;
printf("Greeting message: %s\n", greeting );
return 0;
}
READING STRING FROM TERMINAL
– char line[80];
– scanf(“%s”,line);
– printf(“%s”,line);
• Will read a line of input from the keyboard and display the same on the
screen.
PRINTING STRING
PROGRAM1
main( ) OUTPUT:
{
char name[ ] = "Babbage" ; Babbage
int i = 0 ; Using puts:Babbage
while ( i <= 6 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
printf(“Using puts:”);
puts(name);
}
PRINTING STRING
main( )
PROGRAM2
{ OUTPUT:
char name[ ] = "Babbage" ;
int i = 0 ; Babbage
while ( name[i]!=‘\0’ )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
EXAMPLE PROGRAM
#include <stdio.h>
main()
{
char line[100]; OUTPUT:
int i=0;
Enter Text
printf("Enter Text:\n"); String Programs
String Programs
do
{
line[i]=getchar();
i++;
} while(line[i-1] != '\n');
line[i] = '\0';
printf("\n%s\n",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.
EXAMPLE PROGRAM
#include<stdio.h>
main()
{
char string1[30], OUTPUT
string2[30]; Enter a string Str2:Europe
int i; Str1: Europe
printf("Enter a string Str2:"); Number of characters =6
scanf("%s",string2);
for(i=0;string2[i]!='\0';i++)
string1[i]=string2[i];
string1[i] = '\0';
printf("\n");
printf("Str1:%s\n",string1);
printf("Number of
characters = %d\n",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 AND
• 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 AND
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.
PUTTING STRINGS
TOGETHER
• We cannot assign the string to another directly.
• We cannot join two strings together by the simple arithmetic
addition
string3 = string1 + 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.
STRING-HANDLING
FUNCTIONS
• C library supports large number of string- handling functions
• Some are
FUNCTION ACTION
strlen(s1) Finds the length of the string
strcpy(s1,s2) Copies one string over another
strcat(s1,s2) Concatenates two strings
strcmp(s1,s2) Compares two strings
strchr(s1,ch) Finds a character in string
strstr(s1,s2) Finds the substring
strrev(s1) Reverse the string
String
•
s
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.
#include <stdio.h>
int main()
{
char str[100],i;
printf("Enter a string: \n"); OUTPUT
scanf("%s",str); Enter a string:
College
// '\0' represents end of String Length of input string: 7
for(i=0; str[i]!='\0'; ++i);
printf("\nLength of input string: %d",i);
return 0;
}
Length 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
strcpy()
Function
• 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]; OUTPUT
int i; Enter string s1:
printf("Enter string s1: "); Copycat
scanf("%s",s1); String s2: Copycat
for(i=0; s1[i]!='\0'; ++i)
{
s2[i]=s1[i];
}
s2[i]='\0';
pr
intf("Stri
ng s2:
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
Exampl
#include <stdio.h>
e
#include <string.h>
int main () OUTPUT:
{ Enter text1
The Earth
char s1[50], s2[50];
Enter text2
puts(“Enter text1”);
is Beautiful
gets(s1);
Final destination string:
puts(“\nEnter text2”);
The Earth is Beautiful
gets(s2);
strcat(s1, s2);
printf("Final destination
string: |%s|", s1);
}
C program to concatenate two strings without using strcat()
#include<stdio.h>
void main(void)
{
char str1[25],str2[25]; OUTPUT:
int i=0,j=0;
printf("\nEnter First String:"); Enter First String: The Earth
gets(str1); Enter Second String:is Beautiful
printf("\nEnter Second
String:"); Concatenated String is: The Earthis Beautiful
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++; i++;
}
str1[i]='\0';
printf("\nConcatenated
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(name1, 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.
C program to compare two strings using strcmp
#include <stdio.h>
#include <string.h>
int main()
{ OUTPUT
char a[100], b[100]; Enter the first string
printf("Enter the first string\n"); Hello
gets(a); Enter the second string
printf("Enter the second string\n"); Hai
gets(b); Entered strings are not equal
if( strcmp(a,b) == 0 )
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\
n");
}
C program to compare two strings without using strcmp()
#include <string.h>
if(dif>0)
#include<conio.h> printf("%s comes after %s",str1,str2);
void main(void) else
{ {
char str1[25],str2[25]; if(dif<0)
int dif,i=0; printf("%s comes after %s",str2,str1);
else
clrscr();
printf("Both the strings are
printf("\nEnter the first String:");
same");
gets(str1);
}
printf("\nEnter the second String:");
}
gets(str2);
OUTPUT
while(str1[i]!='\0'||str2[i]!='\0')
Enter the first String: Compare
{ Enter the second String:Compare
dif=(str1[i]-str2[i]); Both the strings are same
if(dif!=0)
break;
i++;
}
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");
strlwr() Function
• The strlwr function converts upper case characters of string to lower case characters.
• The syntax is: strlwr(str1);
//* Program to converts input string to lower case characters */
#include <stdio.h>
#include <string.h>
main()
{
char first[80];
printf("Enter a string: ");
gets(first);
printf("Lower case of the string is %s”,strlwr(first));
}
OUTPUT:
Enter a string: LOWER
Lower case of the string is lower
SOME MORE STRING-HANDLING
FUNCTIONS
FUNCTION ACTION
strncpy(s1,s2,n) Copies up to n characters from the string s1, to
s2. In a case where the length of s2 is less than
that of n, the remainder of s1 will be padded
with null bytes.
strncat(s1,s2,n) Appends the string s2 to the end of the string
s1 up to n characters long.
strncmp(s1,s2,n) Compares at most the first n bytes of s1 and
s2.
Program using strncpy()
#include <stdio.h>
#include <string.h>
int main ()
{ OUTPUT
char src[40]; Final copied string : This is an
char dest[12];
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
Program that initializes 3 names in an array of strings and display them on to monitor
#include<stdio.h>
#include<string.h> OUTPUT
main() Alex
{
Phillip
int i;
Collins
char names[3][10] =
{“Alex”,
“Phillip”,“Collins” };
for(i=0; i<3; i++) printf(“%s\
n”,names[i]);
}
Search a name in a given list
#include<stdio.h>
#include<string.h> if(flag==1)
int main() printf("String found\n");
{ else
char name[5][10],found[10]; printf("\nString not found");
int j,i,flag=0;
printf("Enter the names:\n"); }
for(i=0;i<5;i++)
scanf("%s",name[i]); OUTPUT
printf("Enter the name to be searched:"); Enter the names:
scanf("%s",found); Alice
for(i=0;i<5;i++) Ziya
{ Celene
if(strcmp(name[i],found)==0) Ronald
{ Bob
flag=1; break; } Enter the name to be searched:
} Ram
String not found
Sorting of strings
#include<stdio.h>
}
int main() }
{ }
int i,j,n; printf("The sorted strings are:\n");
char str[20] for(i=0;i<n;i++)
[20],temp[20]; puts(str[i]);
puts("Enter the no. of string to be sorted:"); }
scanf("%d",&n);
for(i=0;i<=n;i++)
gets(str[i]); OUTPUT
for(i=0;i<=n;i++) Enter the no. of string to be sorted:3
{ Ziya
Ronald
for(j=i+1;j<=n;j++)
Bob
{ The sorted strings are:
if(strcmp(str[i],str[j])>0) Bob
{ Ronald
strcpy(temp,str[i]); Ziya
strcpy(str[i],str[j]);
strcpy(str[j],temp);
References
• https://www.tutorialspoint.com/c_standard_library/c_function_
• slideshare.com
THANK YOU