Friday, March 6, 2009

Strings in C

Strings
What is a string ?

Any data enclosed in double quotes like “ Welcome” is termed as a string in C . The data structure used to represent a string could be an array or a pointer

E.g char name[20] = “Focus Systems”;
Here name is an array holding the string “Focus Systems”
char *str = “Team work”
Here str is a pointer . It is the starting address of the string str . It holds
the address of the first letter ‘T’

End of string marker : ‘\0’
Every string is characterized by an end of string marker ‘\0’ (backslash zero or null character or ascii 0 ). This indicates that the string fininshes here . Thus memory allocation for a string is 1 more than the number of characters in it.

String length :
The length of a string is the number of characters in a string including space , tabs , new lines . It does not include ‘\0’

String.h :
The header file string.h contains several useful functions for string manipulations like strlen() , strcpy() , strcmp(), strcat() etc
Some Commonly used string functions are :
strcpy( ) :Copies one string into another
Prototype : char *stpcpy(char *dest , const char *src);
strcpy( ) function copies the string src to dest, stopping after the terminating null character of src has been reached.

strlen( ) : Calculates length of a string
Declaration: size_t strlen(const char *s);
strlen( ) calculates the length of s. Returns the number of characters in s, not counting the terminating null character.

strcmp( ) compare two strings
stricmp( ) , strcmpi( ) compares two strings without case sensitivity
Declaration :
int strcmp(const char *s1, const char*s2);
int strcmpi(const char *s1, const char *s2)
int stricmp(const char *s1, const char *s2);
strcmp() performs an unsigned comparison of s1 to s2.
strcmpi() or stricmp() performs an unsigned comparison of s1to s2, without case sensitivity. The string comparison starts with the first character in each string and continues with subsequent characters until the corresponding characters differ or until the end of the strings is reached.

strcat( ) Appends one string to another
Declaration: char *strcat(char *dest, const char *src);
Strcat( ) appends a copy of src to the end of dest. The length of the resulting string is strlen(dest) + strlen(src). strcat returns a pointer to the concatenated
strings.

strchr( ) Scans a string for the first occurence of a given character
Declaration: char *strchr(const char *s, int c);
strchr scans a string in the forward direction, looking for a specific character.
It finds the first occurrence of the character c in the string s.The null-terminator of the string; for Program strchr(strs, 0) returns a pointer to the terminating character of the string str.


Strings and Dynamic memory allocation :-
As strings are often represented as pointer we may often require to allocates some memory and then read a string into that pointer variable.

For e.g
void main( )
{
char *p ;
p = (char *) malloc (80 * sizeof(char) ) ;
if ( p == NULL )
{
printf(“Allocation failure”);
return 1 ;
}
printf(“Enter a line of text :- “);
gets(p);
printf(“\nYou entered %s” , p );

}

Strings and 2d arrays :-
A data structure like char str[10][80] can be used to store a maximum of 10 strings each with a maximum size of (80 – 1 ) characters whether we use or not a space of 10 X 80 X sizeof(char) is allocated here .

Strings and Array of Pointers :-
A data structure like char *ptr[10] can be used to store 10 strings of varying lengths. Here you allocate memory as and when needed using malloc( ) function . ptr[0] , ptr[1] , ptr[2] … each point to a different location holding a different (length) string . The advantage here is that memory is not blocked unutilized.

E.g:- Program accepts lines of text from the user and outputs in alphabetically sorted order. The program swaps pointers to read data in a sorted order rather than rearranging data to

# define MAXSIZE 10

main( )
{
char *ptr[MAXSIZE] , str[80] ;
char ans = ‘y’ ;
int j , k , len , count ;

clrscr( ) ;

j = 0 ;

while( (ans == ‘y’ || ans == ‘y’ ) && j < len =" strlen(str);"> 0 )
break ; /* At least one string was input so proceed further */
else
return 1 ; /* no strings were input */
}

j++;
printf(“\nOne more line to input ? [y/n] :- “);
fflush(stdin);
ans = getchar( ) ;
}

count = j ; /* count holds number of lines entered */

printf(“\n\nYou entered %d lines of text in this order :\n\n” , count);

for(j = 0 ; j < j =" 0" k =" j+1"> 0 ) /* Compare lines */
{
/* Now swap pointers
char *t ;
t = ptr[ j ] ;
ptr[ j ] = ptr [ k ] ;
ptr [ k ] = t ;
}

printf(“\n\n The lines are sorted as follows :- \n\n”);

for(j = 0 ; j < count ; j++ )
puts ( ptr [ j ] );

getch( );
return 0 ;

}

Why do we call fflush(stdin) in the above program ?

stdin is a pointer to the input ( keyboard buffer) stream . When ever we input data we press the enter key as an indication that the input is over. Next time we attempt to read a character as an input this enter key gets read as an input. This prevents us from reading any further input.A call to the function fflush( stdin ) clears the input buffer of any key that might be lingering .

No comments: