12 Strings
12 Strings
12 Strings
Arrays-II
(Non-numeric arrays)
What is a string?
One-dimensional array of characters
String-handling functions
Two-dimensional array of characters
What is a string?
Variables of type char can hold only a single character, so they have limited usefulness. We
also need a way to store strings, which are sequences of characters. A person's name and
address are examples of strings. Although there is no special data type for strings, C handles
this type of information with arrays of characters.
“A string is an array of characters terminated by a NULL character”
e.g., “I Love India” is a string. Whenever a string is stored in memory, the compiler
automatically inserts a NULL character (\0) at the end of string. This NULL character is a string
terminator, i.e., it denotes the end of string. This NULL character is the first ASCII character
which has a value of zero.
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
I L o v e I n d i a \0
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] a[12]
2
Reading and Printing:
There are 3 ways to read a string using keyboard:
By using scanf() function
By using gets() function
By using getchar() repeatedly (with the help of loops)
There are 3 ways to print a string onto the monitor:
By using printf() function
By using puts() function
By using putchar() repeatedly (with the help of loops)
By using the scanf() and printf() functions: The scanf() function with the conversion
character %s can be used to read a string using keyboard. The printf() function with the same
conversion character can be used to print a string onto monitor. E.g.,
#include<stdio.h>
main()
{
char str[25];
printf(“\n Enter your name:”);
scanf(“%s”,str);
printf(“\n Your Name=%s”,str);
}
Usually, scanf() statement expects an address of the variable. Because the name of the array
itself is an address of it, we don’t use an ampersand (&) before the name of the string. The %s
option uses a blank space as a delimiter and hence it considers the character separated by
blank space as two strings.
The disadvantage of scanf() function is that there is no way to read a multi-word string
(i.e., string with spaces) into a single variable. The scanf() function terminates the input string
when it finds blank space in input string. E.g., if the input for scanf() function is “pradeep
kumar”, the string variable str holds only the string pradeep.
To read a multi-word, we can use the following form of scanf():
#include<stdio.h>
main()
{
char str[25];
printf(“\n Enter your name:”);
scanf(“[^\n]”,str);//[^\n] means read set of characters except new line character
printf(“\n Your Name=%s”,str);
By using the gets() and puts() functions: The gets() function can also be used to read a
string using keyboard. It reads and assigns the input string to the character array until the
ENTER key is pressed. The input string can consist of blank spaces and tabs as part of it. The
puts() function is used to print that string which was read by using gets() or scanf().
3
Ex:
#include<stdio.h>
main()
{
char str[25];
printf(“\n Enter your name:”);
gets(str);
puts(str);
}
The string can be entered until the ENTER key is pressed and can be stored in string variable.
Now, suppose that we input the string “pradeep kumar”. Then the variable str holds the whole
string “pradeep kumar”.
The disadvantage of gets() function is that it can be used to read only one string at a
time. E.g., the following gets() statement is invalid:
gets(str1,str2); //invalid
The gets() function expects only one string as an argument. If more than one string is input to
this function, the compiler gives an error “too many arguments to function gets”
However, a scanf() function can be used to read more than one string at a time.
E.g., scanf(“%s%s%s”,str1,str2,str3); can be used to read 3 strings.
By using a loop: A string can be read character by character by using a for loop (or any
loop). Each time the loop runs, the getchar() function takes the character from the keyboard
and that character will be assigned to the one of character array’s locations. The loop should
be stopped when the new line character is encountered. When the repetition has stopped, the
last location should occupy the NULL character for denoting the end of string.
For printing the string using a loop, the iterative process should start at 0 th location and
should terminate before the NULL character. In each iteration, the character should be printed
with the help of putchar() or printf() with %c conversion specifier.
E.g.,
#include<stdio.h>
main()
{
char str1[23],ch;
int i;
printf("\n Enter any string:");
for(i=0;(ch=getchar())!='\n';i++)
str1[i]=ch;
str1[i]='\0';
for(i=0;str1[i]!=’\0’;i++)
putchar(str1[i]);
}
4
Examples:
5
/*Program to count no.of lines, words /* Program to compare two strings*/
and characters in multiple lines of text*/ #include<stdio.h>
#include<stdio.h> main()
main() {
{ char str1[20],str2[20];
char text[150],ch; int count1,count2;
int nl=0,nw=0,nc=0; puts(“\nEnter first string”);
printf(“\n Enter multiple lines of text (end with gets(str1);
#):”); puts(“\n Enter second string”);
for(i=0;(ch=getchar())!=’#’;i++) gets(str2);
{
nc++; count1=0;
if(ch==’ ‘) for(i=0;str1[i]!=’\0’;i++)
nw++; count1++;
else if(ch==’\n’)
nl++; count2=0;
else ; for(i=0;str2[i]!=’\0’;i++)
} count2++;
printf(“\n No.of lines=%d”,nl);
printf(“\n No.of words=%d”,nc); if(count1!=count2)
printf(“\n No.of characters=%d”,nc); printf(“\n Strings are not equal”);
} else
{
/* Program to concatenate two strings*/ for(i=0;i<count1;i++)
#include<stdio.h> {
main() if(str1[i]==str2[i])
{ {
char str1[40],str2[20]; c=0;
int count; break;
puts(“\nEnter first string”); }
gets(str1); else if(str1[i]>str2[i])
puts(“\n Enter second string”); {
gets(str2); c=1;
break;
count=0; }
for(i=0;str1[i]!=’\0’;i++) else
count++; {
c=-1;
for(i=0;str2[i]!=’\0’;i++) break;
str1[count++]=str2[i]; }
str1[count]=’\0’; }
if(c==0)
printf(“\n concatenated string=%s”,str1); printf(“\n Two strings are equal”);
} else if(c>0)
printf(“\n first string is greater”);
else
printf(“\n Second string is bigger”);
}
}
6
String handling functions
C supports a number of string handling functions. All of these built-in functions are
defined in the header file string.h. Therefore, whenever we use one of these string handling
functions, we should add the preprocessor statement #include<string.h> to our program.
Some of the string- handling functions are:
strcmp()
strcpy()
strcat()
strlen()
strrev()
strncmp()
strncpy()
strncat()
strlwr()
strupr()
strchr()
strcmp() function: This function compares two strings character by character (ASCII
comparison) and returns one of three values {-1,0,1}. Its syntax is as follows:
strcmp(string1,string2);
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”ABC”;
char str2[]=”abc”;
int ans;
ans=strcmp(str1,str2);
printf(“\n Answer=%d”,ans);
}
Here ASCII value of A (i.e 65)is less than a(i.e 97).thus,the above statement returns -32(i.e
65-97) and is assigned to ans.
7
strcpy() function: This function is used to copy one string to the other. Its syntax is as
follows: strcpy(string1,string2);
strcat() function: This function is used to concatenate two strings. i.e., it appends one string
at the end of the specified string. Its syntax as follows:
strcat(string1,string2);
8
strrev() function: This function is used to find the reversed string of a given string. Its
syntax is as follows: strrev(string1);
strncmp() function: This function compares the first n characters of two input strings and
returns one of these 3 values {-1,0,1} same as strcmp() function. Its syntax is as follows:
strncmp(string1,string2,n);
where string1 and string2 are the one-dimensional arrays of characters and n is an integer.
e.g., string1 holds master and string2 holds minister and n=4, then strncmp()
compares first 4 characters of both of these strings character by character and returns the
value (i.e., -1) as strcmp() returns.
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”master”;
char str2[]=”minister”;
int value;
value=strncmp(str1,str2,4);
printf(“\n Returned value=%d”,value);
}
strncpy() function: This function compares the first n characters of second string to the first
string. Its syntax is as follows:
strncpy(string1,string2,n);
where string1 and string2 are the one-dimensional arrays of characters and n is an integer.
e.g., string1 holds Delhi and string2 holds Bangalore and n=4, then strncpy() copies
the first 4 characters of string2 to string1. The string1 holds the copied substring Bang.
9
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”Delhi”;
char str2[]=”Bangalore”;
strncpy(str1,str2,4);
printf(“\n copied string=%s”,str1);
}
strncat() function: This function concatenates the first n characters of second string to the
first string. Its syntax is as follows:
strncat(string1,string2,n);
where string1 and string2 are the one-dimensional arrays of characters and n is an integer.
e.g., string1 holds Master and string2 holds System and n=3, then strncpy()
concatenates or adds the first 3 characters of string2 to string1. The string1 holds the
concatenated string MasterSys.
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”Master”;
char str2[]=”System”;
strncat(str1,str2,3);
printf(“\n concatenated string=%s”,str1);
}
strlwr() function: This function converts all the uppercase alphabets into lowercase. Its
syntax is as follows:
strlwr(string1);
strupr() function: This function converts all the lowercase alphabets into uppercase. Its
syntax is as follows:
strupr(string1);
10
where string1 is the one-dimensional arrays of characters.
e.g., string1 holds Master MINDS, then strupr() converts all the lowercase alphabets of
string1 to uppercase. The string1 holds the upprecase string MASTER MINDS.
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”Master MINDS”;
strupr(str1); /* Alternative for this strlwr() is toupper(str1)*/
printf(“\n converted string=%s”,str1);
}
strchr() function: This function searches for a specified character in a given string. If that
string holds specified character, strchr() function returns first occurrence of character;
otherwise NULL. Its syntax is as follows:
strchr(string1,ch);
Function Purpose
strrchr(string,char) Returns the last occurrence of a specified character in the string.
strcmpi(string1,string2) Compares string2 to string1 with out considering case of text.
strncmpi(string1,string2,n) Compares at most n characters string2 to string1 ignoring case.
stpcpy(string1,string2) Same as strcpy() except it returns string2+strlen(string1).
strdup(string1) Returns the duplicate copy of string1.
strstr(string1,string2) Finds the first occurrence of substring string2 in string1.
strset(string1,char) Sets all the characters of string1 to a given character.
strnset(string1,char,n) Sets all the first n characters of string1 to a given character.
11
Two-dimensional array of characters
By using one-dimensional array, only one string (including spaces) is accepted and processed.
Some times, it is necessary for us to process group of strings. In such situations, we need a
two-dimensional array. A two-dimensional array of characters is an array of one-dimensional
arrays of characters. This means that, a two-dimensional character array consists of strings as
its individual elements.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
names[0] R a j k u m a r \0
names[1] S a n j a n a \0
names[2]
P o o j a \0
Reading and printing multiple strings: The above three methods will be very helpful in
reading and printing each string with the help of a loop. The loop is used for keeping track of
loop counter of rows of two-dimensional array. The following example clears this concept:
12
#inlcude<stdio.h>
main()
{
char names[10][15];
int n,i;
printf(“\n How many strings:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\n Enter %d string:”,i+1);
scanf(“%s”,names[i]);
}
printf(“\n Given strings are:”);
for(i=0;i<n;i++)
printf(“%s\t”,names[i]);
}
Examples:
/*A program to sort strings in /*A program to search for a string in
alphabetical order*/ multiple strings*/
#inlcude<stdio.h> #inlcude<stdio.h>
#include<string.h> #include<string.h>
void sort(char [][],int); int search(char [][],int,char[]);
main() main()
{ {
char names[10][15]; char names[10][15],ele[15];
int n,i; int n,i,pos;
printf(“\n How many strings:”); printf(“\n How many strings:”);
scanf(“%d”,&n); scanf(“%d”,&n);
for(i=0;i<n;i++) for(i=0;i<n;i++)
{ {
printf(“\n Enter %d string:”,i+1); printf(“\n Enter %d string:”,i+1);
scanf(“%s”,names[i]); scanf(“%s”,names[i]);
} }
sort(names,n); printf(“\nEnter string to search);
} scanf(“%s”,ele);
void sort(char names[][],int n) pos=search(names,n,ele);
{ if(pos<=0)
int i,j; printf(“\n String is not found”);
char temp[15]; else
for(i=0;i<n;i++) printf(“\nString is found at %d position”,pos);
{ }
for(j=i+1;j<n;j++) void sort(char names[][],int n,char ele[])
{ {
if(strcmp(names[i],names[j])>0) int i,pos=-1;
{ for(i=0;i<n;i++)
strcpy(temp,names[i]); {
strcpy(names[i],names[j]); if(strcmp(names[i],ele)==0)
strcpy(names[j],temp); {
} pos=i+1;
} break;
} }
printf(“\n Strings in alphabetical order:”); }
for(i=0;i<n;i++) return pos;
printf(“%s\t”,names[i]); }
}
13