Monday, May 12, 2008

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 str[20] = “Focus Systems”;

Here str 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 Two dimensional 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 <>

{

printf(“Enter a line of text :- “);

fflush(stdin); /* Clear input buffer */

gets( str ) ; /* Accept a string from the user */

len = strlen(str); /* length of the input string */

/* allocate memory by calling malloc( )

malloc( ) returns a pointer to a location big enough to hold len + 1 characters .

The +1 is for holding the ‘\0’ the string terminator character

*/

ptr[ j ] = (char *) malloc( (len+1) * sizeof(char) ) ;

/* Did malloc( ) succeed ? */

if ( ptr[ j ] == NULL )

{

printf(“\nAllocation failure “);

if( j > 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 <>

puts ( ptr [ j ] );

/* Now sort the lines using exchange sort algorithm */

for(j = 0 ; j <>

for( k = j+1 ; k <>

if(strcmp( ptr [ j ] , ptr [ k ] ) > 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 <>

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 .

DMA - Dynamic memory allocation

This means memory is allocated for a variable at runtime as and when a request is made .When we use char pointers to store data , we usually have just declared a pointer like char *ptr . Here ptr is allocated a memory of 2 bytes only.If we now want to store data we first have to allocate enough memory for that data . We have to call malloc( ) . In that call we have to specify how many bytes of space we need . malloc() returns a pointer to such a location

malloc( ) : The function malloc( ) Allocates memory

Declaration : void *malloc(size_t size);

malloc( ) allocates a block of size bytes from the memory heap. It allows a program to allocate memory explicitly as it's needed, and in the exact amounts needed. On success, malloc returns a pointer to the newly allocated block of memory. On error (if not enough space exists for the new block), malloc returns null. contents of the block are left unchanged.If the argument size == 0, malloc returns null.We have to explicitly typecast the kind of pointer we want as malloc() returns a void * by default . A void pointer is called as a generic pointer. It can be typecast into different types of pointers

free( ) : The function free( ) is called with pointers to free the memory allocated with malloc( )

e.g free(ptr);

No comments: