Pre-defined Functions in C

  1. strlen :
  • Useful for calculating the length of a string not include \0.
  • Synopsis :
#include<string.h>
size_t strlen(const char *s);
  //size_t is a integer type
  //const - Here strlen not modify the data because of const.
  • It will return a number of character in s means length.

2. strcpy & strncpy :

  • It will copy the source string into destination string.
  • Synopsis:
#include<string.h>
char *strcpy(char *destination , const char *source);
char *strncpy(char *destination , const char *source , size_t n);

strcpy – Copy source string into destination string including \0.

strncpy – We can copy n characters into the destination from the source string.

i.e. embedded\0
     strncpy(destination , source , 4);
     Answer : embed

 

  • Here we can copy 4 byte of source string into destination if in this 4 byte \0 is not there than \0 is not copied into the destination.
  • Note: We have to take  \0 and need to put into destination string at the end of string

3. strchr & strrchr :

  • It will locate the character in string.
  • Synopsis:
#include<string.h>
char *strchr(const char *s,int c);
char *strrchr(const char *s,int c);
  • strchr returns a pointer to the first occurrence of the character c in the string.
  • Same for strrchr but opposite strrchr returns a pointer to the last occurrence of the character c in the string.
  • Both return a pointer to the matched character or NULL if the character is not found.

4. strcat & strncat:

  • Concatenate two string
  • Synopsis:
#include<string.h>
char *strcat(char *destination,const char *source);
char *strncat(char *destination, const char *source, size_t n);
  • This function appends the source string to the destination string, overwrite the null byte at the end of destination.
  • Similar, to strncpy(), strncat() appends only given number of character into destination.

5. strstr:

  • Finding the substring in the main string.
  • Synopsis:
#include<string.h>
char *strstr(const char *haystack, const char *needle);
//haystack - main string's base address
//needle - substring's base string

For example :

main string -  embedded
sub string  - dded
  • Here substring is present into main string so, it will return starting address from where it matches.
  • If a substring is not present in the main string than strstr() will return NULL.

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: