Featured Post

Thursday, October 13, 2016

String handling in C


   A string is a collection of characters i.e., string is a character array. Every character array in C ends with null character '\0'.  All string handling functions are defined  in header file string.h

char a[30]; /* declaration of character array 'a' and 30 bytes will be allocated to 'a' in memory by                                       compiler*/

initialisation of character array 

char a[10]="ashok"; /* initialises first five characters with ashok and remaining characters with null                                        character */

Also we can initialise the array using the following syntax:

char a[10]={'a','s','h','o','k'};



/* sample program */

main()
{
   char a[10]="ashok";
   printf("%s",a);
}
OUTPUT:
      ashok

gets() and puts() functions
 
   gets() function is used to read a string from the keyboard
   puts() function is used to display a string on the screen

/* C program to read a string from keyboard and display the same on the screen */

main()
{
     char a[30];
     printf("enter your name");   /* can be replaced with puts("enter your name"); */
    gets(a);    /* can be replaced by scanf("%s",&a); */
    puts(a);
}

OUTPUT:
           enter your name
           ashok
           ashok 

note: scanf() function exits when a space is entered through keyboard 

The following are the some of the built-in functions in C

strlen()  :    This function accepts one string argument and returns the length of the string

strlcmp(): This function accepts two strings and returns zero if both string are equal otherwise 1

strcat():   This function accepts two string and concatenates one string to another string

strcpy():  This function accepts two parameters and copy one string to another string

strupr():  This function converts the given string to upper case

strlwr():  This function converts the given string to lower case

strrev():  This function reverse the given string

/* C program using built function */
#include<string.h>
main()
{
   char a[30],b[30],c[30];
  int length;
   printf("enter the first string");
   gets(a);
   printf("enter the second string");
   gets(b);
   length=strlen(a);
   printf("\n length of first string is %d",length);
   strcpy(str1,str3);
   printf("c=%s",c);
   printf("\n reverse of a given string %s is %s", c,strrev(c));
   printf("\n concatenation of %s and %s is %s",a,b,strcat(a,b);
   printf("\n upper case of %s is %s", a,strupr(a));
  }

OUTPUT:
     enter the first string
     ashok
     enter the second string
     kumar
     length of first string is 5
     c=ashok
     reverse of a given string ashok is kohsa
     concatenation of ashok and kumar is ashokkumar
     upper case of ashok is ASHOK


string handling in c, character arrays, string handling built functions in c, strcat(), strcmp(), strcpy(), strrev(), strlen(), string palindrome, sample progrma on string built in functions 




No comments:

Post a Comment