Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 10

Handling of character strings

A string is nothing but a group of characters. The group of characters will be treated as
arrays in C-language. Any group of characters defined within double quotes is treated
as strings.
Example: “I am learning about strings in C-language”
Till now whatever you provided in printf statements are character strings only, they
provided some meaningful and readable information to the user.

Declaring and initializing string variables:


A string variable is like an ordinary variable and is always declared as an array. The
general syntax to declare a string variable is

char string-name[size];

the size in a character string represents the number of characters that a character
string can hold. Each character of the string can be treated as an element of the array
name and is stored in the memory. For example if you assign a string “NEW DELHI”,
then it will be stored as follows

‘N’
‘E’
‘W’
‘‘
‘D’
‘E’
‘L’
‘H’
‘I’
‘\0’

When the compiler recognizes the variable as string variable it terminates it with an
additional character ‘\0’ at the end.

Initializing the string variables:


The variables of string can be initialized in two forms:

providing the value as string constant

Example: char city[10]=”hyderabad”;


Initializing each value as a single character like integer arrays.

Example: char city[10]={‘h’,’y’,’d’,’e’,’r’,’a’,’b’,’a’,’d’,’\0’}

NOTE: whenever e initialize a character array by listing elements( as in second method)


we must supply explicitly the null terminator.
C also permits to initialize a character array without size also, in such cases the length
of string will be the actual size of the array.

Assignment of string constants to a string variable:


The assignment of string constant to a string can be done either by using strcpy (dest,
source) of string.h headerfile or reading/writing from the terminal with the help of printf()
and scanf() functions. The input function scanf() is used to read the data from the
console and the output function printf() to write the data to the console with the help of
type specifier %s. The general syntax for using %s is as follows
“%w.p s”
where w stands for width of the string and p stands for precision, but here precision is
the number of characters to be printed.

Here are the examples to explain about strings:


Example1:
main()
{
char name[10];
strcpy(name,”ramesh”);
printf(“ the name=%s”,name);
}

while reading the sting data the ‘&’ sign is not required before the variable name
because a character string is always represents a pointer to that string.
Example2:
main()
{
char name[10];
printf(“enter a name:”)
scanf(“%s”,name);
printf(“ the name=%s”,name);
}

The scanf function terminates whenever a white space or new-line character


encounters. That is the reason when we make use of scanf function the input must be of
only one word. If we want to provide a string with spaces then make use of the following
convention

scanf(“[^\n]s”, variable);
Example3:
main()
{
char str1[10],str2[10];
printf(“enter a name without spaces :”)
scanf(“%s”,str1);
printf(“ the name=%s”,str1);
printf(“enter a name with spaces :”)
scanf(“%s”,str1);
scanf(“%s”,str2);
printf(“ the name in str1=%s”,str1);
printf(“ the name in str2=%s”str2
}

Example4:
main()
{
char str1[10],str2[10];
printf(“enter a name without spaces :”)
scanf(“%s”,str1);
printf(“ the name=%s”,str1);
printf(“enter a name with spaces :”)
scanf(“%[^\n]s”,str2);
printf(“ the name in str2=%s”str2
}

NOTE: The type specifier “[^\n]s “ can be applicable only when we use scanf() it is not
valid for printf(). It directs the compiler to accept the string till ‘ \n ‘ encounters.

Accessing the characters of a string:


Each character of a string can be accessed with its index value. The following example
explains about this.
Example 4:

main()
{
int i;
char name[10];
printf(“enter a name:”)
scanf(“%s”,name);
for(i=0;name[i]!=’\0’;i++)
printf(“ the character in name[%d] =%c\n”,name[i]);
}

Example 5:
Write a C-program to find the length of a string
main()
{
char string[10];
int i;
printf(“enter a string:”);
scanf(“%d”, string);
for(i=0;string[i]!=’\0’;i++);
printf(“the length of string is %d”, i);
}
There is function in string.h header file which helps to find the length of string i.e.
strlen().

The general syntax for this function is n=strlen(string) where n is an integer


Example 6:

Write a program to copy a string to another string


main()
{
char string1[10], string2[10];
int i;
printf(“enter a string in lower case:”);
scanf(“%[^\n]s”,string1);
for(i=0;string1[i]!=\0;i++)
string2[i] =string1[i];
string2[i]=’\0’;
printf(“The copied string is = %s”,string2);
}
There is function in string.h header file which copies a string to another string i.e.
strcpy().

The general syntax for this function is strcpy(string1,string2)

NOTE: While copying of strings the source length should be equal or more than that of
the destination string so as to accommodate the length of both the strings.

write a program to print a string in the following format.

programing
programin
programi
program
progra
progr
prog
pro
pr
p

Example7:

#include<string.h>
#include<stdio.h>
main()
{
static char str[12]="programing";
int i,len,w;
clrscr();
len=strlen(str);
for(i=0,w=len;str[i]!='\0';i++,len--)
printf("%-*.*s\n",w,len,str);
getch();
}
In the above program first * in type-specifier is for width and second * for precision. We
can also specify the integer constants instead of * like,

printf(“%-12.*s\n”,len,str);

Arithmetic operations on strings:


C allows manipulating the characters in the same way as we do with numbers. To print
a character constant as an integer we can make use of %d. this specifier prints the
ASCII value of that particular character constant.

Example 8: program to print ASCII values of characters


main()
{
int i;
for(i=0;i<256;i++)
printf(“the ASCII value of %c is%d”,i,i);
}
Whenever a character constant or character variable is used in an expression, the
system automatically converts it into an integer value. Hence it is possible to make
arithmetic operations on characters.
Example 9:

write a program to convert a lower case string to upper case


main()
{
char name[10];
int i;
printf(“enter a string in lower case:”);
scanf(“%[^\n]s”,name);
for(i=0;name[i]!=\0;i++)
name[i]-=32;
name[i]=’\0’;
printf(“%s”,name);
}
There is function in string.h header file which converts a string of lower case to upper
case i.e. toupper().

Two strings cannot be added directly using addition operator(+) the statement such as
string3 =string1+ string2 is not valid the process of adding two strings is known as
concatenating. The following program explains the logic for concatenation.
Example10:

write a program to concat a string to another string


main()
{
char string1[10], string2[10];
int i,j;
printf(“enter a string in lower case:”);
scanf(“%[^\n]s”,string1);
for(i=0;string1[i]!=\0;i++);
string1[i]=’ ’;
for(j=0;string2[j] != ‘\0’;j++)
string1[i+j+1] =string2[j];
string2[i+j+1]=’\0’;
printf(“The concatenated string is = %s”,string1);
}
There is function in string.h header file which concatenates two strings i.e. strcat().

The general syntax for this function is strcat(string1,string2)

NOTE: While catenation of strings the source string (string1) length should be double or
more than that of the destination string(string2) so as to accommodate the addition
length of both the strings.
Example for the usage of strcat():
main()
{
char str1[20],str2[10];

printf(“enter first string less than 10 characters:”);


scanf(“%s”,str1);

printf(“enter second string less than 10 characters:” );


scanf(“%s”,str2);
strcat(str1,” “);

printf(“ The string str1 after concat with a white space = %s* ”, str1);

strcat(str1,str2);
printf(“ The string str1 after concat with str2 = %s”, str1);
}
Output:
enter first string less than 10 characters: John
enter first string less than 10 characters: Travolta
The string str1 after concat with a white space = John *
The string str1 after concat with str2 = John Travolta

Comparison of two strings:


C does not permit to compare two strings directly. Statement like string1==string2 is not
valid. If you want to compare two strings then the comparison is done character by
character. The comparison will be carried out in a loop with condition until there is a
mismatch of character or any of the strings may terminate to null character. Here is an
example which explains about it.
Example 11:

main()
{
char str1[10],str2[10]
int i;
printf(“enter first string);
scanf(“%s”,str1);
printf(“enter second string);
scanf(“%s”,str2);
i=0;
while((str1[i++]==str2[i]) && str1[i]!=’\0’ && str2[i] !=’\0’)
i++;
if(str1[i]==’\0’ && str2[i]==’\0’)
printf(“Both are Equal”);
else
printf(“Both are not Equal”);
}

There is function in string.h header file which helps to compares two strings i.e.
strcmp(). This function returns an integer value, which is the difference between the
ASCII values of differed characters of two strings.

If the differences between characters of first string and second string is that of positive,
then the first string is greater than second one.
If the differences between characters of first string and second string is that of negative,
then the first string is less than second one.
If the difference between characters of first string and second string is that of zero, then
both the strings are equal.
The general syntax for this function is strcmp(string1,string2)
Example for strcmp()
main()
{
char str1[10],str2[10]
int i;
printf(“enter first string);
scanf(“%s”,str1);
printf(“enter second string);
scanf(“%s”,str2);
if(strcmp(str1,str2)==0)
printf(“Both are Equal”);
else if(strcmp(str1,str2)>0)
printf(“str1 is greater than str2”);
else
printf(“str1 is less than str2”);
}

Reading a line of text:


To read a line of text from the terminal getchar() function is used . This function reads
character by character from the console. This function is used repeatedly to read the
characters from the console and place them into a character array.
The reading is terminated whenever ‘\n’ is encountered.

Example:
main()
{
char line[50],ch;
int i=0;
printf(“enter the line of text and press return at the end:”);
do
{
ch = getchar();
line[i]=ch;
i++;
}while(ch!=’\0’);
i - -;
line[i]=’\0’;
printf(“the entered line is = %s”, line);
}
Two-dimensional string arrays:
A list of names is treated as a table of strings. Whenever it is necessary to store multiple
names with only one variable name, it is necessary to declare the variable as two-
dimensional array. The declaration is like an integer array.

Data-Type variable-name[index1][index2]

In the above syntax index1 indicates the number of students and index2 indicates the
length of each string. For example if the variable is declared as name[5][20] then it
indicates that the variable name can be able to hold 5 names with a length of 20
characters each.

Initialization of two-dimensional string variable:


This can be done as follows:

static type variable-name[ ][ ]={“string-1”,”string-2”,…, “string-n”};

example: [static] char city[ ][ ]={“GUNTUR”,”VIZAG”,HYDERABAD”};

To access the name of city at ith location access that with its index value i.e. if want to
access the city HYDERABAD in the array then access it with its index city [2]. Once an
array is declared as two-dimensional array, it can be accessed like a one-dimensional
array in further manipulations.

Program for sorting of names


main()
{
char string[10][20],temp[20];
int i , j ,n;
printf(“enter number of names you want to enter:”);
scanf(“%d”,&n);
printf(“enter the names:”);
for(i=0;i<n;i++)
scanf(“%s”, name[i]);

/* Process for sorting of names */


for(i=0; i<n-1; i++)
for(j=i+1; j<n; j++)
if(strcmp(name[i],name[j])>0)
{
strcpy(temp , name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
for(i=0;i<n;i++)
printf(“%s”, name[i]);
}

You might also like