Sunday, December 11, 2016

String Functions in C

1. strlen()
This function counts and returns number of characters from the string. It takes the following form:
n = strlen(string);



char name[10] = “Yellow”;
int len;
len = strlen(name); //’len’ will be 6.




2. strcat()
This function joins two strings together. That is, this function is used to concatenate the strings. It takes the following general form:
strcat(string1, string2);


char str1[ ] = “New”;
char str2[ ] = “Delhi”;
strcat(str1, str2);
printf(“%s”, str1); //outputs “NewDelhi”
printf(“%s”, str2); //outputs “Delhi”
We can concatenate / join a string constant to the string variable such
as:
strcat(str1, “York”);
printf(“%s”, str1); //outputs “NewYork”


3) strcpy()
This function almost works like string-assignment operator. That is, strcpy() function is used to copy contents of one string into another.It takes the following general form:
strcpy(string1, string2);
This will copy contents of string1 into string2.
For example:
char city1[5] = “Pune”;
char city2[5];
strcpy(city2, city1);
printf(“%s”, city1); //outputs “Pune”
printf(“%s”, city2); //outputs “Pune”
We can also use the constant as the parameter to the strcpy(). Such
as:strcpy(city2, “Pimpri”);


 4. strcmp()
This function is used to compare two strings and accordingly
returns the value. That is, it returns the numerical difference between
the strings. It takes the following general form:
strcmp(string1, string2);
Chapter 03 Arrays and Strings
Programming in ‘C’ by Mr. Kute T. B. - 12 -
Here, string1 and string2 may be string variables or strings
constants. The function will compare the strings and returns the value.
if this value of 0, implies that both the strings are equal. If it is
positive, implies that string1 is greater and if negative, implies that
string2 is greater. For example:
strcmp(city1, city2);
strcmp(“Pune”, city1); etc.
This function is case-sensitive function. The case-insensitive form of
this function is also available given below:
strcmpi(string1, string2); or
stricmp(string1, string2);



5. strrev()
This function reverses the contents of the string. It takes the following
general form:
strrev(string);
Here, the ‘string’ is the string variable whose value is to be reversed.
For example:
char str[10] = “Sakeena”;
strrev(str);
printf(“%s”, str); //print aneekaS on the screen.


No comments:

Post a Comment