Pages

  • Home
  • About & Contact
  • Archive
  • C Programming Examples

19 February 2012

String functions in C with examples

What are strings?
In simple language STRING'S are nothing but the character array.The declaration of string (character array) is much similar to normal array declaration.Each string is terminated by '\0' as indication of string termination.So obviously you will require an extra byte of memory for storing '\0'.'\0' is single character whose ASCII (American Standard Code for Information Interchange) value is 0.

How to initialize strings (char array)?
char site[]={'g','o',o','g','l','e'.};
char Site[]="Programmingspark";

How to take Input as string and print Output that string?
way 1:
void main()
{
    char name[30];
    printf("Enter your name");
    scanf("%s",name);       //format specifier
    printf("%s",name);
}

way 2:

void main()
{
     char name[30];
     printf("Enter your name");
     gets(name);         //in-built function
     puts(name);
}

Difference between both ways is that 1st way use's format specifier and second way uses in-built function.
In 1st way if you Enter something like john karter it will take only john as string and any thing after (space) will be discarded.In second way if you enter any space it will be accepted.Output of second way would be john karter.

Similarity between both way is that you don't have to add '\0' character.
scanf(%s ) converts 32(space) or '\n' character into '\0' and  gets() converts newline character '\n' into '\0'.

List of string functions in c.
strlen     strcpy    strcat     strrev      strcmp    strcmpi     strupr      strlwr     strncmpi
strncat      strncmp    strncmpi      strncmpi.

String functions examples
1) int strlen(char array):This function accepts string as parameter and return integer i.e the length of  String  passed to it.

Example
#include <stdio.h>
#include <string.h>
void main(void)
{
   char string[]="spark";
   int len;
   len=strlen(string);
   printf("length of %s is %d\t",string,len);
}


Output::length of spark is 5.
Did you notice that strlen() does not include '\n' in string length or else length would be 6.


2) strcpy (Destination string,source string):This function accepts 2 strings as parameter,1st one is destination string and 2nd is source string.This function copies source string to destination string.

Example
#include <stdio.h>
#include <string.h>
void main(void)
{
   char src[]="spark",dest[15];
   strcpy(dest,src);
   printf("%s is copied to dest string\t",dest);
}
Output:spark is copied to dest string.

3) strcat (Destination string,source string): This function accepts two,strings source string is appended to the destination string.

Example
#include <stdio.h>
#include <string.h>
void main(void)
{
   char src[]="spark",dest[]="programming";
   strcat(dest,src);
   printf("concatenated string is %s",dest);
}
Output:concatenated string is programmingspark


4) strrev (string):This function accepts single string as parameter and reverse that string.

Example
#include <stdio.h>
#include <string.h>
void main(void)
{
   char string[]="spark";
   strrev(string);
   printf("reverse string is %s",string);
}
Output: reverse string is kraps.

5)int strcmp (string 1, string2):This function compares two strings passed as parameters and returns either +ve number,0,-ve number.

+ve value indicates string1 > string2.
0 indicates string1 and string2 are equal
-ve value indicates string1 < string2.

Example
#include <stdio.h>
#include <string.h>
void main(void)
{
   char string1[]="spark",string2[]="programming";
   int cmp;
   cmp=strcmp(string1,string2);
   if(cmp>0)
      printf("%s > %s",string1,string2);
   else
   {
   if(cmp<0)
       printf("%s < %s",string1,string2);
   else
printf("%s = %s",string1,string2);
  }
}

Output: spark > programming.
.this is because alphabetically p comes first then s.so the string compare function returns difference between ascii of s and p which would be +ve.

6) strcmpi (string 1, string2):This function is similar to strcmp().The onlyy difference is that it ignores the case.example SparK and spark both are same.

Example
#include <stdio.h>
#include <string.h>
void main(void)
{
   char string1[]="spark",string2[]="SPArk";
   int cmp;
   cmp=strcmpi(string1,string2);
   if(cmp>0)
      printf("%s > %s",string1,string2);
   else
   {
   if(cmp<0)
       printf("%s < %s",string1,string2);
   else
printf("%s = %s",string1,string2);
  }
}

Output: spark = SPArk.

7) strlwr (string)::This function accepts single string that can be in any case(lower or upper).It converts the string in lower case.

Example
#include <stdio.h>
#include <string.h>
void main(void)
{
   char string1[]="SPArk";
   strlwr(string1);
   printf("%s is in lower case",string1);

}
Output: spark is in lower case.

8) strupr (string)::This function accepts single string that can be in any case(lower or upper).It converts the string in upper case.

Example
#include <stdio.h>
#include <string.h>
void main(void)
{
   char string1[]="SPArk";
   strupr(string1);
   printf("%s is in upper case",string1);

}

Output: SPARK is in upper case.

9)char* strstr (main string,substring): This function accepts two strings i.e main string and substring.
It searches for the first occurrence substring in main string and returns the character pointer to the first char.

Example

#include <stdio.h>
#include <string.h>
void main()
{
       char str1[]="programmingspark",str2[]="ming",*ptr;
       ptr=strstr(str1, str2);
       printf("substring is: %s",ptr);
       getch();
}


Output : substring is mingspark 
Hope you found this page useful.

Recommended programs:

c program to convert string to lowercase without using strlwr [ using pointers]

C program to reverse a string without using string functions [ using pointers ]


Share your views regarding the given post via the comments section given below.
If you liked the post, please '+1' it & share it on other social networks.
Thank You.

24 comments:

  1. It is very effective to revise before my exam

    ReplyDelete
  2. it's very helpful to me..thank you

    ReplyDelete
    Replies
    1. I am glad that it proved to be helpful to you!!

      Delete
  3. Write a program that uses an array of pointers to strings str[ ].
    Receive two strings str1 and str2 and check if str1 is embedded in any of the strings in str[ ].
    If str1 is found, then replace it with str2.
    char *str[ ] = {
    "We will teach you how to...",
    "Move a mountain",
    "Level a building",
    "Erase the past",
    "Make a million",
    "...all through C!"
    } ;

    For example if str1 contains "mountain" and str2 contains "car",
    then the second string in str should get changed to "Move a car".

    ReplyDelete
  4. Write a program that uses an array of pointers to strings str[ ].
    Receive two strings str1 and str2 and check if str1 is embedded in any of the strings in str[ ].
    If str1 is found, then replace it with str2.
    char *str[ ] = {
    "We will teach you how to...",
    "Move a mountain",
    "Level a building",
    "Erase the past",
    "Make a million",
    "...all through C!"
    } ;

    For example if str1 contains "mountain" and str2 contains "car",
    then the second string in str should get changed to "Move a car".

    ReplyDelete
    Replies
    1. The code is ready,but not in optimized form
      before using this code,optimize it and remove the unnecessary variables

      #include
      #include
      #include
      void main()
      {
      char *str[]={"we will teach you how to","move a mountain" ,"level a building","erase the past","make a million","all through c!"};
      char *str3[20];
      char str1[25],str2[25],temp[25];
      int len1,len2,len3,i,j,k,x,count1,count2;
      printf("Enter both the strings");
      scanf("%s%s",str1,str2);
      len1=strlen(str1);
      len2=strlen(str2);
      for(i=0;i<6;i++)
      {
      count1=0;count2=0;
      for(k=0;k<=strlen(str[i]);k++)
      {
      if(str[i][k]==' '||str[i][k]=='\0')
      {
      temp[count1]='\0';
      x=strcmp(str1,temp);
      count1=0;
      if(x==0)
      {
      x=strlen(str2)-strlen(temp);
      if(x>0)
      {
      len3=strlen(str[i]);
      str[i][len3]=' ';
      for(j=len3;j!=k;j--)
      {
      str[i][j+x]=str[i][j];
      }
      str[i][len3+x]='\0';
      strcat(str2," ");
      len2++;
      }
      else
      {
      for(j=k;str[i][j]!='\0';j++)
      {
      str[i][j+x]=str[i][j];
      }
      str[i][j+x]='\0';
      }
      count2=0;
      for(j=k-len1;j<k-(len1-len2);j++)
      {
      str[i][j]=str2[count2++];
      }

      }
      }
      else
      temp[count1++]=str[i][k];

      }
      }
      for(i=0;i<6;i++)
      {
      puts(str[i]);
      }
      getch();

      }

      Delete
  5. Write a program that uses an array of pointers to strings str[ ].
    Receive two strings str1 and str2 and check if str1 is embedded in any of the strings in str[ ].
    If str1 is found, then replace it with str2.
    char *str[ ] = {
    "We will teach you how to...",
    "Move a mountain",
    "Level a building",
    "Erase the past",
    "Make a million",
    "...all through C!"
    } ;

    For example if str1 contains "mountain" and str2 contains "car",
    then the second string in str should get changed to "Move a car".

    ReplyDelete
    Replies
    1. the code has been pasted above

      Delete
  6. ummm-hmmm....not getting the correct output... can u plz check my program


    #include
    #include
    #include
    int main()
    {
    char *str[]= {
    "we will teach you how to....",
    "Move a mountian",
    "Level a bulding",
    "Erase the Past",
    "Make a Million",
    "...all through C"
    };
    char str1[20],str2[20];
    char *p,*t,*news;
    int i;

    printf( "Enter the string to be replaced :");
    gets(str1);

    printf ( "Enter the new string : ");
    gets(str2);

    if(strlen(str2)> strlen(str1))
    {
    printf( "enter the string with %d characters only",strlen(str1));
    exit(0);
    }

    for( i=0; i<=5; i++)
    {
    p=strstr(str[i],str1);

    if(p)
    {
    news=p+strlen(str1);
    strcpy(t,news);
    strcpy(p,str2);
    strcat(p,t);
    break;
    }
    }
    printf( "the new string \n:");
    for(i =0; i<=5; i++ )
    printf( "%s\n",str[i]);
    return 0;
    }

    ReplyDelete
    Replies
    1. Your program is working correctly
      it has one problem that if second string is longer than first 1 than this program will not work

      if you still have any problem then ask..

      Delete
  7. @romil...
    im novice programmer ,,plz point out error in my program,, and repost it..plzzz.
    and 1 more thing ....
    i forgot how to use hmmm,,,while loop for yes or no ....
    it will ask do u want to continue ,,,, if yes then,,,,it will continue... else
    exit...
    plz write a simple program for,,,, me ....so I'll get a clue....

    ReplyDelete
  8. your program is working perfectly without any bugs
    I dont know whats your problem is?

    and do while loop thing is here

    #include
    #include
    #include
    int main()
    {
    char *str[]= {
    "we will teach you how to....",
    "Move a mountain",
    "Level a building",
    "Erase the Past",
    "Make a Million",
    "...all through C"
    };
    char str1[20],str2[20];
    char *p,*t,*news;
    int i,ch;
    do
    {

    printf( "Enter the string to be replaced :\n");
    scanf("%s",str1);

    printf ( "Enter the new string : ");
    scanf("%s",str2);

    if(strlen(str2)> strlen(str1))
    {
    printf( "enter the string with %d characters only",strlen(str1));
    exit(0);
    }

    for( i=0; i<=5; i++)
    {
    p=strstr(str[i],str1);

    if(p)
    {
    news=p+strlen(str1);
    strcpy(t,news);
    strcpy(p,str2);
    strcat(p,t);
    break;
    }
    }
    printf( "the new string \n:");
    for(i =0; i<=5; i++ )
    printf( "%s\n",str[i]);
    printf("\nPress 2 to continue: ");
    scanf("%d",&ch);
    }while(ch==2);
    return 0;
    }

    ReplyDelete
    Replies
    1. can you please explain it wht the value in p=strstr(str[i],str1)
      after program
      please explain it

      Delete
  9. cant strcat() conctenate two strings and place it in the third?

    ReplyDelete
    Replies
    1. No, the Built-in strcat() will not concatenate two strings in the third string but you can create your own function that can concatenate two strings into third string

      Delete
  10. cant strcat() conctenate two strings and place it in the third?

    ReplyDelete
  11. can you please tell me the example programe for preprocessor in c language

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Q. Write a function that returns the index of the last occurrence of a substring in a string.
    for eg. "abc abcxyz diff abckk"
    the output should be 17,as the substring "abc" occurs three times and counting the index(from 0) of each letter and the spaces as well, we get the index of last "a" as 17 which is occurring in the last substring "abc".

    ReplyDelete
  14. very helpful for my seminar....thank you.

    ReplyDelete
  15. Can you tell me how to make program for this condition:
    given string is : "Where there is a will,there is a way";
    output string is: "Where there is a will,way";

    how to make program for that string?

    ReplyDelete
  16. the last example. strstr(mainstring, substring) is helpful! thank you very much!

    ReplyDelete

Back To Top