Array Nonnumeric
Array Nonnumeric
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.
e.g., “AMRITA” 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.
The string that can hold an array of characters can be declared with the following syntax:
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.
Initializing a string
This one-dimensional array of characters can be initialized by using assignment operator as
follows:
char a[13]= {‘A’,’M,’R’,’I’,’T’,‘A’};
is equivalent to
char a[13]=”AMRITA”;
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[]={‘A’,’M,’R’,’I’,’T’,‘A’,\0’} ;
is equivalent to
char a[]=”AMRITA”;
If I can say
char a[]=”AMRITA”;
Why can’t I say
char a[13];
a=”AMRITA”;
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,”AMRITA”);
This is how static initialization takes place to assign string to character [Link] let us look into
how dynamic initialization is done.
Reading and printing a string
There are 3 ways to read a string using keyboard:
By using scanf() function (formatted input function)
By using gets() function (unformatted input 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 (formatted output function)
By using puts() function (unformatted output 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>
int 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 “AMRITA
College”, the string variable str holds only the string AMRITA
To read a multi-word, we can use the following form of scanf():
#include<stdio.h>
int main()
{
char str[25];
printf("\n Enter your name:");
scanf("%[^\n]s",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().
Ex:
#include<stdio.h>
int 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 “Amrita college”. Then the variable str holds the whole
string “Amrita college”.
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 or any other delimiter specified. 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 0th 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.
#include<stdio.h>
int 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]);
}
Some examples::
/*A program to check whether given string is palindrome or not*/
#include<stdio.h>
int main()
{
char str[30];
int len=0,flag=0,i,j;
printf("\n Enter a string:");
gets(str);
for(i=0;str[i]!='\0';i++)
len++;
for(i=0,j=len-1;i<j;i++,j--)
if(str[i]!=str[j])
{
flag=1; OUTPUT:
break; Enter a string:madam
}
if(flag==0) Given string is palindrome
printf("\n Given string is palindrome");
else
printf("\n Given string is not a palindrome");
}
#include<stdio.h>
int main()
{
char text[50];
int i;
printf("\n Enter a line of text:");
gets(text);
for(i=0;text[i]!='\0';i++)
{
if(text[i]>='A' && text[i]<='Z') OUTPUT:
text[i]=text[i]+32; Enter a line of text:AmRiTa
else
text[i]=text[i]-32;
}
converted text=aMrItA
printf(“\n converted text=%s”,text);
}
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);
2. strrev() function: This function is used to find the reversed string of a given string. Its syntax is
as follows:
strrev(string1);
3. strcpy() function:
This function is used to copy one string to the other. Its syntax is as follows:
strcpy(string1,string2);
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);
int strcmp(string1,string2);
#include<stdio.h>
int main()
{ char str1[20],str2[20];
int x,i,c;
printf("\n Enter first string:");
scanf("%s",str1);
printf("\n Enter second string:");
scanf("%s",str2);
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;
}
}
if(c==0) OUTPUT:
printf("\n Both strings are equal"); Enter first string:master
else if(c>0)
printf("\n First string is bigger"); Enter second string:minds
else
printf("\n Second string is bigger"); Second string is bigger
}
This function converts all the uppercase alphabets into lowercase. Its syntax
is as follows:
strlwr(string1);
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.
[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:
Method 1 using scanf() and printf()::
#include<stdio.h>
#include<string.h>
int 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]);
}
for(i=0;i<n;i++) OUTPUT:
{ How many strings:3
for(j=i+1;j<n;j++)
{ Enter 1 string:rajkumar