Arrays II

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

Arrays-II 10

(Non-Numeric Arrays)
0

Chapter Outline
“There are basically two types of people. People
10.1. Introduction.
who accomplish things and people who claim to
have accomplished things. The first group is less 10.2. One-Dimensional
crowded.” -Mark Twain
array of characters.
10.3. String-handling
functions.
10.4. Two-Dimensional
array of characters.
“We must remember that one determined 10.5. Conclusion
person can make a significant difference, and
that a small group of determined people can
change the course of history.” -Sonia Johnson

“The greater the loyalty of a group toward the


group, the greater is the motivation among the
members to achieve the goals of the group, and
the greater the probability that the group will
achieve its goals.” -Rensis Likert
10.1. Introduction
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.

10.2. One-Dimensional array of characters


10.2.1. Declaring a string
The string that can hold an array of characters can be declared with the following syntax:

<Storage_class> char <array_name>[size];

In this syntax:
<Storage_class> is any one of auto, extern, static or register, an optional one.
char is the data type that determines the type of elements in the array are as characters.
<array_name> is any valid identifier.
size, a positive integer constant or integer constant expression, determines the number of characters in
the string.
Ex: char name[20]; //can hold a string of 19 characters; one location is for NULL
char a [35]; //can hold a string of 34 characters; one location is for NULL
When we declare a character array, a memory location should be reserved for the NULL character.

10.2.2. Initializing a string


This one-dimensional array of characters can be initialized by using assignment operator as follows:
char a[13]={‘I’,’ ‘,’L’,’o’,’v’,’e’,’ ‘,’I’,’n’,’d’,’I’,’a’};
is equivalent to
char a[13]=”I Love India”;
In both of the cases, the NULL character can be appended to the string automatically. If the length of the
string is exceeded than the specified size in square brackets, then the compiler gives the error. This error
can be rectified with the help of the following initialization statement that automatically allocates memory
based on the number of characters in that string:
char a[]={‘I’,’ ‘,’L’,’o’,’v’,’e’,’ ‘,’I’,’n’,’d’,’I’,’a’};
(or)
char a[]=”I Love India”;
When the character array is initialized, the memory map for that array is as follows:

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]

Interview question #1
If I can say
char a[]=”I Love India”;
Why can’t I say
char a[13];
a=”I Love India”;
As we know that strings are arrays. As we can’t assign arrays directly, strings can’t be assigned
directly. Instead, we can use strcpy() like this:
strcpy(a,”Hello world”);

10.2.3. Reading and printing a string


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)

10.2.3.1. 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);
}
10.2.3.2. 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().
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.
10.2.3.3. 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]);
}
Example programs:
/*A program to check whether given /*Program to count no.of vowels and
string is palindrome or not*/ consonants in a line of text*/
#include<stdio.h> #include<stdio.h>
main() main()
{ {
char str[30]; char text[50];
int len=0,flag=0,i,j; int nv=0,nc=0;
printf("\n Enter a string:"); printf(“\n Enter a line of text:”);
gets(str); gets(text);
for(i=0;str[i]!='\0';i++) for(i=0;text[i]!=’\0’;i++)
len++; {
for(i=0,j=len-1;i<j;i++,j--) if(text[i]==’a’||text[i]==’e’||text[i]==’o’||
if(str[i]!=str[j]) text[i]==’i’||text[i]==’u’)
{ nv++;
flag=1; else
break; nc++;
} }
if(flag==0) printf(“\n No.of vowels=%d”,nv);
printf("\n Given string is palindrome"); printf(“\n No.of consonants=%d”,nc); }
else
printf("\n Given string is not a
palindrome");
}
/*Program to count no.of lines, words /*Program to convert the case of text*/
and characters in multiple lines of #include<stdio.h>
text*/ main()
#include<stdio.h> {
main() char text[50];
{ printf(“\n Enter a line of text:”);
char text[150],ch; gets(text);
int nl=0,nw=0,nc=0; for(i=0;text[i]!=’\0’;i++)
printf(“\n Enter multiple lines of text (end {
with #):”); if(text[i]>=’A’ && text[i]<=’z’)
for(i=0;(ch=getchar())!=’#’;i++) text[i]=text[i]+32;
{nc++; else
if(ch==’ ‘) text[i]=text[i]-32;
nw++; }
else if(ch==’\n’) printf(“\n converted text=%s”,text);
nl++; }
else ;
}
printf(“\n No.of lines=%d”,nl);
printf(“\n No.of words=%d”,nc);
printf(“\n No.of characters=%d”,nc); }
Passing a string to a function
To pass a string to a function, these rules should be followed:
 The function must be called by passing only the name of the string, without the subscript.
 In the function definition, the formal parameter must be a character array type; the size of the
array does not need to be specified.
 The function prototype must show that the argument is a character array.
The following program demonstrates the concept of passing a string to a function:

Ex: /* A program to count the number of occurrences of a character in a string*/


#include<stdio.h>
void display(char[]); //function prototype
int getCount(char[],int);//function prototype
main()
{
char str[30],ch;
int c;
printf(“\n Enter any string:”);
gets(str);
display(str); //function call
printf(“\n Enter the character to be searched:”);
scanf(“\n%c”,&ch);
c=getCount(str,ch); //function call
if(c>0)
printf(“\n the character %c is occurred %d times”,ch,c);
else
printf(“\n The given character is not found”);

}
void display(char s[]) //function definition
{
printf(“\n Given string=%s”,s);
}
int getCount(char s[],char ch) //function definition
{
int count=0,i;
for(i=0;s[i]!=’\0’;i++)
if(s[i]==ch)
count++;
return count;
}
/* A program to convert a string to a /* A program to convert an integer to a
number*/ string*/
#include<stdio.h> #include<stdio.h>
int str_to_int(char []); #include<string.h>
main() char * int_to_str(int);
{ main()
char str[10]="1234"; {int n = 1234;
printf("number = %d",str_to_int(str)); printf("string is %s",int_to_str(n));
} }
int str_to_int(char str[]) char * int_to_str(int n)
{ {static char str[10];
int i,sum=0; char temp;
for(i=0;str[i]!='\0';i++) int i=1,j;
{ if(n>=0)
if(str[i]=='-' && i==0) str[0]='+';
continue; else
sum = sum*10 + (str[i]-'0'); {str[0]='-';
} n = -n;}
if(str[0]=='-') for(;n>0;n=n/10)
sum = -sum; str[i++] = n%10+'0';
return sum; str[i]='\0';
} for(i=1,j=strlen(str)-1;i<j;i++,j--)
{temp = str[i]; str[i] = str[j]; str[j] = temp;}
return str;
}

/*A program to convert a string to float*/ /*A program to convert a float to string*/
#include<stdio.h> #include<stdio.h>
char * float_to_str(float);
float str_to_float(char *);
main()
main() {float n = -1234.1234;
{ char str[20]="-1234.12345"; printf("string is %s",float_to_str(n));
printf("number = %f",str_to_float(str)); }
char * float_to_str(float p)
}
{static char str[10];
float str_to_float(char *str) char temp;
{ int i,x=0,y=10; int i=1,j,k,n,m;
float sum=0; if(p>=0)
str[0]='+';
for(i=0;str[i]!='\0';i++)
else
{ if(str[i]=='-' && i==0) { str[0]='-';
continue; p = -p;}
if(str[i]=='.') m = n = p;
{x=1; for(;n>0;n=n/10)
str[i++] = n%10+'0';
continue;} p = p-m;
if(x==0) for(j=1;j<=4;j++)
sum = sum*10 + (str[i]-'0'); p = p*10;
else n=p;
str[i]='.';
{ sum = sum + (str[i]-'0')/(float)y; k = i;
y=y*10; for(i++;n>0;n=n/10)
}} str[i++] = n%10+'0';
if(str[0]=='-') str[i]='\0';
for(i=1,j=k-1;i<j;i++,j--)
sum = -sum; {temp = str[i]; str[i] = str[j]; str[j] = temp; }
return sum;} for(i=k+1,j=strlen(str)-1;i<j;i++,j--)
{temp = str[i]; str[i] = str[j]; str[j] = temp;}
return str;
}
10.3. String-handling functions
C supports a number of string handling functions. All of these built-in functions are aimed at
performing various operations on strings. 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:
strlen() strrev() strcpy() strcat() strcmp()
strlwr() strupr() strncpy() strncat() strncmp()

1. strlen() function: This function is used to find the length of the string excluding the NULL character.
In other words, this function is used to count the number of characters in a string. Its syntax is as follows:

int strlen(string1);

where string1 is the one-dimensional array of characters.


This function returns an integer value that is the count of characters in the string. E.g., string1
contains pradeep is a good boy then strlen(string1) function returns the value 21.

/* A program to calculate length of string by /* A program to calculate length of string


using strlen() function*/ without using strlen() function*/
#include<stdio.h> #include<stdio.h>
#include<string.h> int MyStringLength(char [50]);
main() main()
{ {
char string1[50]; char string1[50];
int length; int length;
printf(“\n Enter any string:”); printf("\n Enter any string:\n");
gets(string1); gets(string1);
length=strlen(string1); length=MyStringLength(string1);
printf(“\n The length of string=%d”,length); printf("\n The length of string=%d",length);
} }
int MyStringLength(char str[50])
{
int len=0,i;
for(i=0;str[i]!='\0';i++)
len++;
return len;
}

2. strrev() function: This function is used to find the reversed string of a given string. Its syntax is as
follows: strrev(string1);

where string1 is the one-dimensional array of characters.


This function stores the reversed string of string1 in that argument string1 only. E.g., string1
contains master then the same string1 contains retsam after execution of strrev() .
/* A program to reverse a string using /* A program to reverse a string without using
strrev() function*/ strrev() function*/
#include<stdio.h> #include<stdio.h>
#include<string.h> void MyStringReverse(char [30]);
main() main()
{ {
char string1[30]; char string1[30];
printf(“\n Enter any string:”); printf("\n Enter any string:");
gets(string1); gets(string1);
strrev(string1); printf("\n Original string=%s",string1);
printf(“\n Reversed string=%s”,string1); MyStringReverse(string1);
} }
void MyStringReverse(char str[30])
{
int length=0,i,j;
char temp;
for(i=0;str[i]!='\0';i++)
length++;
for(i=0,j=length-1;i<j;i++,j--)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
printf("\n Reversed string=%s",str);
}
3.strcpy() function: This function is used to copy one string to the other. Its syntax is as follows:

strcpy(string1,string2);

where string1 and string2 are one-dimensional character arrays.


This function copies the content of string2 to string1. E.g., string1 contains master and string2
contains madam, then string1 holds madam after execution of the strcpy(string1,string2) function.

/* A program to copy one string to another /* A program to copy one string to another
using strcpy() function*/ without using strcpy() function*/
#include<stdio.h> #include<stdio.h>
#include<string.h> void MyStringCopy(char[],char []);
main() main()
{ { char string1[30],string2[30];
char string1[30],string2[30]; printf("\n Enter first string:");
printf(“\n Enter first string:”); gets(string1);
gets(string1); printf("\n Enter second string:");
printf(“\n Enter second string:”); gets(string2);
gets(string2); MyStringCopy(string1,string2);
strcpy(string1,string2); }
printf(“\n First string=%s”,string1); void MyStringCopy(char str1[30],char str2[30])
printf(“\n Second string=%s”,string2); { int i;
} for(i=0;str2[i]!='\0';i++)
str1[i]=str2[i];
str1[i]='\0';
printf("\n First string=%s",str1);
printf("\n Second string=%s",str2);
}
4.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);

where string1 and string2 are one-dimensional character arrays.


This function joins two strings together. In other words, it adds the string2 to string1 and the
string1 contains the final concatenated string. E.g., string1 contains prog and string2 contains ram, then
string1 holds program after execution of the strcat() function.

/* A program to concatenate one string with /* A program to concatenate one string with
another using strcat() function*/ another without using strcat() function*/
#include<stdio.h> #include<stdio.h>
#include<string.h> void MyStringConcat(char[],char[]);
main() main()
{ { char string1[30],string2[15];
char string1[30],string2[15]; printf("\n Enter first string:");
printf(“\n Enter first string:”); gets(string1);
gets(string1); printf("\n Enter second string:");
printf(“\n Enter second string:”); gets(string2);
gets(string2); MyStringConcat(string1,string2);
strcat(string1,string2); }
printf(“\n Concatenated string=%s”,string1); void MyStringConcat(char str1[30],char str2[15])
} { int i,j;
for(i=0;str1[i]!='\0';i++);
for(j=0;str2[j]!=0;j++)
str1[i+j]=str2[j];
str1[i+j]='\0';
printf("\n Concatenated string=%s",str1);
}

5. 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:

int strcmp(string1,string2);

where string1 and string2 are one-dimensional arrays of characters.


When this function is invoked with two strings as arguments, then:
 This function returns -1 or negative integer, if the ASCII value of the character of the first string is
less than that of second string;
 It returns 0 (zero), if both strings are equal;
 It returns 1 or a positive integer, if the ASCII value of the character of first string is greater than
that of the second string.
E.g., string1 contains master and string2 contains minds, then strcmp(string1,string2); returns a
negative value; since the ASCII value of ‘a’ is lesser than the ASCII value of ‘i’.
/* A program to compare two strings using /* A program to compare two strings without
strcmp() function*/ using strcmp() function*/
#include<stdio.h> #include<string.h>
#include<string.h> int MyStringCompare(char[],char[]);
main() main()
{ { char string1[20],string2[20];
char string1[30],string2[15]; int x;
int x; system("clear");
printf(“\n Enter first string:”); printf("\n Enter first string:");
gets(string1); gets(string1);
printf(“\n Enter second string:”); printf("\n Enter second string:");
gets(string2); gets(string2);
x=strcmp(string1,string2); x=MyStringCompare(string1,string2);
if(x==0) if(x==0)
printf(“\n Both strings are equal”); printf("\n Both strings are equal");
else if(x>0) else if(x>0)
printf(“\n First string is bigger”); printf("\n First string is bigger");
else else
printf(“\n Second string is bigger”); printf("\n Second string is bigger");
} }
int MyStringCompare(char str1[],char str2[])
{ int i,c=0;
for(i=0;str1[i]!='\0'||str2[i]!='\0';i++)
{
if(str1[i]>str2[i])
{
c=1;
break;
}
else if(str1[i]<str2[i])
{
c=-1;
break;
}
}
return c;
}

6. strlwr() function: This function converts all the uppercase alphabets into lowercase. Its syntax is as
follows:

strlwr(string1);

where string1 is the one-dimensional array of characters.


e.g., string1 holds Master MINDS, then strlwr() converts all the uppercase alphabets of string1 to
lowercase. The string1 holds the lowercase string master minds.
/* A program to convert an upper case string /* A program to convert an uppercase string
to lower case string using strlwr() function*/ to lowercase string without using strlwr()
#include<stdio.h> function*/
#include<string.h> #include<stdio.h>
main() void MyStringLower(char[]);
{ main()
char string[30]; { char string[30];
printf(“\n Enter any uppercase string:”); printf("\n Enter any uppercase string:");
gets(string); gets(string);
strlwr(string); MyStringLower(string);
printf(“\n lower case string=%s”,string1); }
} void MyStringLower(char str[])
{ int i;
for(i=0;str[i]!='\0';i++)
if(str[i]>='A' && str[i]<='Z')
str[i]=str[i]+32;
printf("\n lower case string=%s",str);
}

7. strupr() function: This function converts all the lowercase alphabets into uppercase. Its syntax is as
follows:

strupr(string1);

where string1 is the one-dimensional array 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.

/* A program to convert a lower case string to /* A program to convert a lowercase string to


upper case string using strupr() function*/ upper case string without using strupr()
#include<stdio.h> function*/
#include<string.h> #include<stdio.h>
main() void MyStringUpper(char[]);
{ main()
char string[30]; { char string[30];
printf(“\n Enter any lower case string:”); printf("\n Enter any lower case string:");
gets(string); gets(string);
strupr(string); MyStringUpper(string);
printf(“\n upper case string=%s”,string); }
} void MyStringUpper(char str[])
{ int i;
for(i=0;str[i]!='\0';i++)
if(str[i]>='a' && str[i]<='z')
str[i]=str[i]-32;
printf("\n Upper case string=%s",str);
}
8.strncpy() function: This function copies 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.

/* A program to copy first n characters of a /* A program to copy first n characters of a


string using strncpy() function*/ string without using strncpy() function*/
#include<stdio.h> #include<stdio.h>
#include<string.h> void MyStringNCpy(char[],char[],int);
main() main()
{ {
char string1[30],string2[30]; char string1[30],string2[30];
printf(“\n Enter first string:”); int n;
gets(string1); printf("\n Enter first string:");
printf(“\n Enter second string:”); gets(string1);
gets(string2); printf("\n Enter second string:");
printf(“\n How many characters:”); gets(string2);
scanf(“%d”,&n); printf("\n Enter howmany characters:");
strncpy(string1,string2,n); scanf("%d",&n);
printf(“\n First string=%s”,string1); MyStringNCpy(string1,string2,n);
} }
void MyStringNCpy(char str1[],char str2[],int n)
{
int i;
for(i=0;i<n;i++)
str1[i]=str2[i];
str1[i]='\0';
printf("\n First string=%s",str1);
}
Interview question #2
How to pick a substring from a given string?
A substring is a part of another string. In order to pick up a substring from a given string, we should
use strncpy() function. E.g., there is a string: master minds. Suppose we want to pick up a substring
mind. Then we can observe that the word mind is located at 7th location in array. From 7th location, we
have to keep track of next 4 characters to pick up the following string. The following program
demonstreates this:
#include<stdio.h>
main()
{
char word[]="Master minds";
char sub[15];
strncpy(sub,&word[7],4);
printf("%s",sub);
}
9. 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.

/* A program to concatenate first n characters /*A program to concatenate first n characters


to a string by using strncat() function*/ to a string without using strncat() function*/
#include<stdio.h> #include<stdio.h>
#include<string.h> void MyStringNCat(char[],char[],int);
main() main()
{ {
char string1[30],string2[30]; char string1[30],string2[30];
printf(“\n Enter first string:”); int n;
gets(string1); printf("\n Enter first string:");
printf(“\n Enter second string:”); gets(string1);
gets(string2); printf("\n Enter second string:");
printf(“\n How many characters:”); gets(string2);
scanf(“%d”,&n); printf("\n Enter howmany characters:");
strncat(string1,string2,n); scanf("%d",&n);
printf(“\n First string=%s”,string1); MyStringNCat(string1,string2,n);
} }
void MyStringNCat(char str1[],char str2[],int n)
{
int i,len;
len=strlen(str1);
for(i=0;i<n;i++)
{
str1[len]=str2[i];
len++;
}
str1[len]='\0';
printf("\n concatenated string=%s",str1);
}

10. 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.
/* A program to compare first n characters of /* A program to compare first n characters of
two strings using strncmp() function*/ two strings without using strncmp()
#include<stdio.h> function*/
#include<string.h> #include<stdio.h>
main() int MyStringNCmp(char[],char[],int);
{ main()
char string1[30],string2[15]; {
int x; char string1[30],string2[30];
printf(“\n Enter first string:”); int n,x;
gets(string1); printf("\n Enter first string:");
printf(“\n Enter second string:”); gets(string1);
gets(string2); printf("\n Enter second string:");
x=strncmp(string1,string2); gets(string2);
if(x==0) printf("\n Enter howmany characters:");
printf(“\n Both strings are equal”); scanf("%d",&n);
else if(x>0) x=MyStringNCmp(string1,string2,n);
printf(“\n First string is bigger”); if(x==0)
else printf("\n Both strings are equal");
printf(“\n Second string is bigger”); else if(x>0)
} printf("\n First string is greater");
else
printf("\n Second string is greater");
}
int MyStringNCmp(char str1[],char str2[],int n)
{ int i,c=0;
for(i=0;i<n;i++)
{ if(str1[i]>str2[i])
{ c=1;
break;
}
if(str1[i]<str2[i])
{ c=-1;
break;
}
}
return c;
}

Other useful string handling functions


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.
10.4. 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 a 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 (i.e., one-dimensional arrays of
characters) as its individual elements.

10.4.1. Declaration: Like Two-dimensional numeric arrays, Two-dimensional character arrays should be
declared before it is used. A Two-dimensional array of characters can be declared as follows:
<Storage_class> char <array_name>[row][column];
where <Storage_class> is any one of auto, extern, static or register, an optional one.
char is the data type that determines the type of elements in the array.
<array_name> is any valid identifier.
row, a positive integer, determines the number of strings in the array.
Column, a positive integer, determines the number of characters a string can hold.
Ex: char a[5][10]; //can hold 5 input strings, each input string should be of length 9 chars.

10.4.2. Initialization: Like One-dimensional character array, a Two-dimensional character array can also
be initialized with the help of assignment operator as follows:
char names[3][10]={ {‘R’,’a’,’j’,’ ’,’k’,’u’,’m’,’a’,’r’},
{‘S’,’a’,’n’,’j’,’a’,’n’,’a’},
{‘P’,’o’,’o’,’j’,’a’}};
is equivalent to
char names[3][10]={“Raj kumar”,”Sanjana”,”Pooja”};
When this Two-dimensional character array is initialized, it will be in memory as follows:

[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

10.4.3. 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:
Method-1: using printf() and Method-2: using gets() Method-3: Using getchar() and
scanf() and puts() putchar() repeatedly
#inlcude<stdio.h> #inlcude<stdio.h> #include<stdio.h>
main() main() main()
{ { { char names[10][15],ch;
char names[10][15]; char names[10][15]; int i,n,j,k;
int n,i; int n,i; printf(“\n How many strings:”);
printf(“\n How many strings:”); printf(“\n How many scanf(“%d”,&n);
scanf(“%d”,&n); strings:”); for(k=0;k<n;k++)
for(i=0;i<n;i++) scanf(“%d”,&n); {printf(“\n Enter %d
{printf(“\n Enter %d for(i=0;i<n;i++) string:”,k+1);
string:”,i+1); {printf(“\n Enter %d for(i=0;(ch=getchar())!='\n';i++)
scanf(“%s”,names[i]); string:”,i+1); names[k][i]=ch;
} gets(names[i]); names[k][i]='\0';
printf(“\n Given strings are:”); } }
for(i=0;i<n;i++) printf(“\n Given strings printf(“\n Given strings are:”);
printf(“%s\t”,names[i]); are:”); for(k=0;k<n;k++)
} for(i=0;i<n;i++) { for(i=0;names[k][i]!=’\0’;i++)
puts(names[i]); putchar(names[k][i]);
} putchar(‘\n’);
}
}

Passing multiple strings to a function


To pass multiple strings to a function, these rules should be followed:
 The function must be called by passing only the name of the character two-dimensional array,
without the subscripts.
 In the function definition, the formal parameter must be a character two-dimensional array type;
the value of the second subscript needs to be specified.
 The function prototype must show that the argument is a character two-dimensional array with
second subscript’s value.
The following programs demonstrate the concept of passing multiple strings to a function:
/*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);
{ int i,j; if(pos<=0)
char temp[15]; printf(“\n String is not found”);
for(i=0;i<n;i++) else
{ printf(“\nString is found at %d position”,pos);
for(j=i+1;j<n;j++) }
{ int search(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]); }
}

/*A program print frequencies of words /* A program to print words those begin
in a line of text*/ with given alphabet*/
#include<stdio.h> #include<stdio.h>
#include<string.h> main()
main() {
{ char **words,alpha;
char str[50],copy[20][20],word[15]; int n,i;
char temp[]=" "; printf("\n Enter how many words:");
int i,j,k,l,count; scanf("%d",&n);
printf("\n Enter a line of text:"); for(i=0;i<n;i++)
scanf("%[^\n]",str); *(words+i)=(char *)malloc(15*sizeof(char));
k=0; printf("\n Enter %d words",n);
for(i=0;str[i]!='\0';i++) for(i=0;i<n;i++)
{ j=i; scanf("%s",*(words+i));
l=0; printf("\n Enter the alphabet based on which
while(str[j]!=' ') words are displayed:");
{ copy[k][l]=str[j]; scanf("\n%c",&alpha);
l++; printf("\n The searched words starts
j++; with \'%c\' are:",alpha);
} for(i=0;i<n;i++)
copy[k][l]='\0'; {
k++; if(words[i][0]==alpha)
i=j; printf("%s\t",*(words+i));
} }
for(i=0;i<k;i++) }
{ count=1;
for(j=i+1;j<k;j++)
{ if(strcmp(copy[i],copy[j])==0)
{
strcpy(copy[j]," ");
count++;
}
}
if(strcmp(copy[i]," ")!=0)
printf("\n%s occured %d
times",copy[i],count);
}
}
10.5. Conclusion
Generally, a string is a collection of characters. In C, just like int represents integer values, there is no
data type that represents strings. Instead, a string is represented as a one-dimensional array of
characters. Each string has one termination character (‘\0’) that denotes the end of string.
In C, there is a header file namely string.h that has different built-in functions which perform
various operations on strings. In order to represent one string (either single word or multi-word), one-
dimensional array is helpful. In order to store multiple strings (either single word or multi-word), two-
dimensional array is helpful.

You might also like