The most commonly used functions in the string library ie. Using <string.h> are:
- strcat - concatenate two strings
- strchr - string scanning operation
- strcmp - compare two strings
- strcpy - copy a string
- strlen - get string length
- strncat - concatenate one string with part of another
- strncmp - compare parts of two strings
- strrchr - string scanning operation
strcat:
char *strcat(char *s1, const char *s2);
s1 is a pointer to a string that will be modified. s2 will be copied to the end of s1. s2 is a pointer to a string that will be appended to the end of s1. It returns a pointer to s1 (where the resulting concatenated string resides).
strcpy:
char *strcpy(char *s1, const char *s2);
s1 is a pointer to the destination. s2 will be copied to the end of s1. It returns a pointer to s1 (where the resulting copied string resides).
strlen:
int strlen(char *s1);
s1 is a pointer to the string. It returns the length of the string excluding ‘\0’ character.
Example –
#include <stdio.h> #include <string.h> int main(int argc, const char * argv[]) { /* Define a temporary variable */ char MyString[100]; /* Copy the first string into the variable */ strcpy(MyString, "a4"); /* Concatenate the following two strings to the end of the first one */ strcat(MyString, "academics "); strcat(MyString, ".com"); /* Display the concatenated strings */ printf("%s\n", MyString); /* Display the length of the string */ printf(“Length : %d\n”,strlen(MyString)); return 0; }
Output –
a4academics.com
Length : 15
a4academics.com
Length : 15
strchr :
char *strchr(const char *s, int c);
s is a string (terminated by a null character).c is the character to be found. It returns a pointer to the first occurrence of the character c within the string pointed to by s. If c isn't found, it returns a null pointer.
strcmp :
char *strcmp(const char *s1, const char *s2);
s1 and s2 a string (terminated by a null character). It returns the ASCII value difference of the first index of mismatched characters of the given string.
Example -
strcmp(“Samiran”,Saha);
It will return the difference between ASCII value of ‘m’ and ‘a’ ie. 12. Because first mismatch occurs at 3rd index.
strcmp(“Saha”,Saha);
It will return 0 because there is no mismatch in the given string.
No comments:
Post a Comment