Thursday, June 2, 2011

C Programs Using Buil-in-String Functions


Today will discuss some useful String functions, string.h is the header in the C/C++ standard library for the C/C++ programming language which contains macro definitions, constants, and declarations of functions and types used not only for string handling but also various memory handling functions. Functions declared in string.h are extremely popular, since as a part of the C/C++ standard library, they are guaranteed to work on any platform which supports C. The string functions only work with ASCII or character sets that extend ASCII in a compatible manner.

String function, which only valid to string type data and string handling is not an easy job in 'C'. Even string.h provide the functions you need but often you will be asked to write your own functions and prohibited from using some of the string function. So, how to do this I will come to this when we talk about programming. In C/C++, while using these following string function you must include "string.h" header file.



strlen() - Returns the number of characters in string, not including the terminating null character.

Syntax : int L=strlen(Str);

Example

/* STRLEN.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main( )
 {
      char Str[61] = "This Sentence are for testing!";
      int len;
      clrscr();      len = strlen(Str);
      printf("\n=========STRLEN================\n");
      printf( "'%s' is having %d characters \n", Str, len );
      getch(); }

Output

=========STRLEN================";

'This Sentence are for testing!' is having 30 characters


strcpy() - The strcpy() function copies Source String, including the terminating null character, to the location specified by Destination String. No overflow checking is performed when strings are copied or appended. The behavior of strcpy is undefined if the source and destination strings overlap.

Syntax : strcpy(dest,src)

Example

/* STRCPY.C*/

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main( )
  {
       char src[80]="I am fit and fine",dest[80];
       strcpy( dest,src );
       clrscr();
       printf("\n=========STRCPY================\n");
       printf( "Source '%s ' and Destination is ' %s'",src,dest);
       getch();

  }

Output

=========STRCPY================

Source 'I am fit and fine ' and Destination is ' I am fit and fine'



strncpy () - The strncpy function copies the initial count characters of Source String to Destination String. If count is less than or equal to the length of Source, a null character is not appended automatically to the copied string. If count is greater than the length of Source, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap.

Sysnatx : strncpy(dest,src,N); // 'N' is Numbers of Characters from left

Example

/* STRNCPY.C */

#include <string.h>
#include <stdio.h>
#include<conio.h>

void main( )
 {
     char src[50] = "String Function, Testing!",dest[50];
     clrscr();
     strncpy( dest, src, 15 );
     dest[15]='\0'; // Terminating with a null
     printf("\n=========STRNCPY================\n");
     printf (" Source ' %s ' and copied first 15 characters to destination '%s'",src,dest);
     getch();
}

Output

=========STRNCPY================

Source ' String Function, Testing! ' and copied first 15 characters to
destination 'String Function'



strcmp() - The strcmp function compares string1 and string2 lexicographically and returns a value indicating their relationship.

Syntax : int L= strcmp(str1,str2 );

Return Value Relationship of string1 to string2

< 0 string1 less than string2

= 0 string1 identical to string2

> 0 string1 greater than string2

Example

/* STRCMP.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main( )
 {
     char str1[50];     char str2[50];
     int result;
     clrscr();
     printf("\nEnter two String : ");
     gets(str1);
     gets(str2);
     printf("\n=========STRCMP================\n");
     printf("\nInput String ' %s ' and ' %s '",str1,str2);
     result=strcmpi(str1,str2);
     if(result==0)
          printf(" Strings are Equal ");
     if(result<0)          printf(" String1 is Smaller than String2 ");
     if(result>0)
          printf(" String1 is bigger than String2 ");  
     getch();
 }

Output

Enter two String : Testing

Testing

=========STRCMP================
Enter two String : Testing

Testing

Input String ' Testing ' and ' Testing '  Strings are Equal

=========STRCMP================

Enter two String : Jest
Test

Input String ' Jest ' and ' Test '
String1 is Smaller than String2

=========STRCMP================

Enter two String : Test
Rest

Input String ' Test ' and ' Rest '
String1 is bigger than String2

=========STRCMP================

Enter two String : test

Test
Input String ' test ' and ' Test ' String1 is bigger than String2



Check the last output in strcmp(), String values 'Test' and 'test' are showing not equal, beacuse strcmp() function is case sensitive, for this you can use strcmpi() or stricmp().

strcmpi() - The strcmpi() function lexicographically compares while ignoring cases of string1 and string2 and returns a value indicating their relationship.Retun Values are same as strcmp().

Syntax : int L= strcmpi( str1, str2 );

Example

/* STRCMPI.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main( )
 {
        char str1[50],str2[50];   
        int result;
        clrscr();
        printf("\nEnter two String : ");
        gets(str1);
        gets(str2);        printf("\n=========STRCMPI================\n");
        printf("\nInput String ' %s ' and ' %s '",str1,str2);
        result=strcmpi(str1,str2);
        if(result==0)
       printf (" Strings are Equal ");
       if(result<0)
       printf(" String1 is Smaller than String2 ");
       if(result>0)
       printf(" String1 is bigger than String2 ");
       getch();
 }

Output

Enter two String : Test
test

=========STRCMPI================

Input String ' Test ' and ' test '  Strings are Equal



strncmp() - Each of these routines compares str1 to str2, looking at no more than 'N' characters from beginning. strnicmp() and strnicmp() perform a signed comparison of s1 to 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 'N' characters have been examined. Return Values are same as strcmp().

Syntax : strncmp(str1,str2,N); //N is numbers of characters from left

Example


/* STRNCMP.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main()
 {
   char str1[50];
   char str2[50];
   int result,N=4;
   clrscr();
   printf("\nEnter two String : ");
   gets(str1);
   gets(str2);
   printf("\n=========STRNCMP================\n");
   printf("\nInput String ' %s ' and ' %s '\n",str1,str2);
  result=strncmp(str1,str2,N);
  if(result==0)
      printf(" First %d character of Strings are Equal",N);
 if(result<0)
      printf(" First %d character String1 is Smaller than String2 ",N);
 if(result>0)
      printf(" First %d character String1 is bigger than String2 ",N);
 getch();
}

Output


Enter two String : Compare
Comparing

=========STRNCMP================

Input String ' Compare ' and ' Comparing ' First 4 character String1 is Smaller than String2

Enter two String : compare
Comparing

=========STRNCMP================

Input String ' compare ' and ' Comparing ' First 4 character String1 is bigger than String2

Enter two String : Compare
compare

=========STRNCMP================

Input String ' Compare ' and ' compare ' First 4 character String1 is Smaller than String2



/* STRNCMPI.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main()
 {
    char str1[50];
    char str2[50];
    int result,N=4;
   clrscr();
   printf("\nEnter two String : ");
   gets(str1);
   gets(str2);
   printf("\n=========STRNCMPI================\n");
   printf("\nInput String ' %s ' and ' %s '\n ",str1,str2);
   result=strncmpi(str1,str2,N);
   if(result==0)
       printf(" First %d character of Strings are Equal",N);
   if(result<0)
      printf(" First %d character String1 is Smaller than String2 ",N);
  if(result>0)
     printf(" First %d character of String1 is bigger than String2 ",N);
  getch();
}

Output


Enter two String : Compare
compare

=========STRNCMPI================

Input String ' Compare ' and ' compare ' First 4 character of Strings are Equal



strcat() - The strcat function appends strSource to strDestination and terminates the resulting string with a null character. The initial character of Source String overwrites the terminating null character of Destination String. No overflow checking is performed when strings are copied or appended. The behavior of strcat is undefined if the source and destination strings overlap.

Syntax : strcat(dest,src);

Example

/* STRCAT.C*/

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main()
 {
     char src[50]="I am Fit.",dest[50]="Iam Fine. ";
     clrscr();
     printf("\n\n============STRCAT===============\n\n");
     printf("Source ' %s ' and Destination ' %s ' concatenated to Destination ",src,dest);
     strcat( dest, src );
     printf(" ' %s '\n",dest);
     getch();
}

Output

============STRCAT===============

Source ' I am Fit. ' and Destination ' I am Fine. ' concatenated to Destination '
I am Fine. I am Fit. '



strncat() - The strncat() function appends, at most, the first count characters of Source string to Destination string. The initial character of  Source string overwrites the terminating null character of destination string. If a null character appears in Source string before count characters are appended, strncat() appends all characters from Source string up to the null character. If count is greater than the length of Source string, the length of  Source stringis used in place of count. The resulting string is terminated with a null character. If copying takes place between strings that overlap, the behavior is undefined.

Syntax : strncat(dest,src,N);// 'N' is numbers of character from left of source string

Example

/* STRNCAT.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

 void main()
  {
      char src[50] = "I Love India & live in too",dest[50]="I live in India, ";
       int N =13;
      clrscr();
      printf("\n\n=================STRNCAT==============\n");
      printf("Srouce : ' %s ' and Destination ' %s '\n", src,dest);
      strncat(dest,src,N );
      printf( " After %d character Concatenate to Destination ' %s '\n", N,dest);
      getch();
  }

Output


=================STRNCAT==============

Srouce : ' I Love India & live in too ' and Destination ' I live in India, '

After 13 character Concatenate to Destination ' I live in India, I Love India '



strchr() - strchr scans a string in the forward direction, looking for a specific character. These functions find the first occurrence of the character c in the strings.

Syntax : char *p = strchr(str, char)

Return Value: On success, returns a pointer to the first occurrence of the character c in string s.

On error (if c does not occur in s), returns null.

Example:

/* STRCHR.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

 void main()
  {
      char str[25]="Searching A Character";
      char *ptr, c = 'r';
      clrscr();
      ptr = strchr(str, c);
      printf("\n\n=================STRCHR==============\n");
      if (ptr)
        printf("The character ' %c ' is at position: %d\n", c, ptr-str);
     else
        printf("The character was not found\n");
    getch();
}

Output

=================STRCHR==============
The character ' r ' is at position: 3



strstr()- Finds the first occurrence of a substring in another string. Scan str1 for the first occurrence of the substring str2.

Syntax : char *p=strstr(str1,str2);

Return Value:
On success, strstr returns a pointer to the element in str1 where str2 begins (points to s2 in s1).

On error (if s2 does not occur in s1), strstr returns null.

Example:

/* STRSTR.c */

#include <stdio.h>
#include <string.h>
#include <conio.h>

void main()
 {
     char str1[] = "Borland International", str2[] = "nation", *ptr;
     ptr = strstr(str1, str2);
     printf("\n\n==================STRSTR================\n");
     printf("Sentence ' %s ' and Search Text ' %s '\n",str1,str2);
     printf("The substring is: %s and the position is %d\n", ptr,ptr-str1);
     getch();
}

Output

==================STRSTR================
Sentence ' Borland International ' and Search Text ' nation '

The substring is: national and the position is 13



strlwr() - Converts the string to uppercase letters (A to Z) in strings to lowercase (a to z).
strupr() - Converts the string to convert lowercase letters (a to z) in string s to uppercase (A to Z).

Syntax : strlwr(Str);
               strupr(str);

Example

/*STRUPR/STRLWR()*/

#include <stdio.h>
#include <string.h>
#include <conio.h>

void main()
 {
      char str[] = "Converting Uppercase to lowercase vice versa";
      clrscr();
      printf("\n\n===============STRLWR===============\n");
      printf("\n String ' %s ' converted to lowercase \n", str);
      strlwr(str);
      printf(" ' %s '\n", str);
      printf("\n\n===============STRUPR===============\n");
      printf("\n String ' %s ' converted to uppercase \n", str);
      strupr(str);
      printf(" ' %s '\n", str);
      getch();
}

Output

===============STRLWR===============

String ' Converting Uppercase to lowercase vice versa ' converted to lowercase '
converting uppercase to lowercase vice versa '

===============STRUPR===============

String ' converting uppercase to lowercase vice versa ' converted to uppercase '
CONVERTING UPPERCASE TO LOWERCASE VICE VERSA '


strrev() - Reverses all characters in str (except for the terminating null)

Syntax : strrev(str);

Example

/*STRREV.c*/

#include <stdio.h>
#include <string.h>
#include <conio.h>

void main()
  {
        char str[] = "Borland C";
        clrscr();
        printf("\n\n===============STRREV===============\n");
        printf("\n Original String ' %s 'After \n", str);
        strrev(str);
        printf(" ' %s '\n", str);
        getch();
  }

Output

===============STRREV===============

Original String ' Borland C ' After ' C dnalroB '




strdup() - Copies a string into a newly created location. strdup() makes a duplicate of string s, obtaining space with a call to malloc().

Syntax : char *p = strdup(str);

Return Value:

On success, returns a pointer to the location containing the duplicated string
On error (if space couldn't be allocated), returns null

Example:

/*STDUP.c*/

#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <alloc.h>

void main()
 {
      char *dup_str, str[] = "abcde";
      clrscr();
      dup_str = strdup(str);
      printf("Original string is ' %s ' duplicated to ' %s '\n", str,dup_str);
      getch();
}

Output

Original string is ' abcde ' duplicated to ' abcde '



strtok() - srtok() consider the string s1 to consist of a sequence of zero or more text tokens, separated by spans of one or more characters from the separator string s2.The first call to strtok returns a pointer to the first character of the first token in s1, and writes a null character into s1 immediately following the returned token. Subsequent calls with null for the first argument will work through the string s1 until no tokens remain. The separator string, s2, can be different from call to call.

Syntax : char *p= strtok( string, delimiter);

Return Value:

On success, returns a pointer to the token found in s1.

When there are no more tokens, returns a null p

Example

/* STRTOK.C: */

#include <string.h>
#include <stdio.h>
#include <conio.h>

 void main( )
  {
        char stok[]="I live in India and India is a beautiful Country";
        char *tok;
        clrscr();
        printf("\n\n===============STRTOK===============\n");
        printf( "%s\n\nTokens:\n", stok );
        tok = strtok( stok, " " ); //Delimiter is space
        while( tok != NULL )
           {
                printf( " %s\n", tok );
                tok = strtok( NULL, " " );
           }
        getch();
  }

Output

I live in India and India is a beautiful Country

Tokens:

I
live
in
India
and
India
is
a
beautiful
Country



!!! Hope it will be helpful to you.!!!

No comments: