08 May 2012

String Functions in 'C' (#include<stdio.h>)

The 'C' language provides a number of functions which help when handling strings.

strcat(string1, string2);

This function concatenates (adds to the end of) string2 to string1.
char string1[30] = "First String", string2[15] = "Second String";
strcat(string1, string2);
printf("%s", string1); // will print First StringSecond String
strlen(string);


This function returns the length of the string, not including the null.
char str[15] = "My Name";
int x = strlen(str);
printf("The length of the string is %d", x);   // will print The length of the string is 7
strcpy(string1, string2);

This function copies the contents of string2 to string1.
char string1[30] = "First String", string2[15] = "Second String";
strcpy(string1, string2);
printf("%s", string1);    // will print Second String
strcmp(string1, string2);

this function compares string1 to string2. the function returns 0 if the strings are equal. it returns < 0 if string1 is < string2, returns > 0 if string1 is > string2.
x = strcmp(string1, string2);
if (x < 0)
{
    printf("string1 is less than string2");
}
or
if (strcmp(string1, string2) == 0)
{
    printf("The strings are equal");
}
String and Character Library Functions (ctype.h and string.h)

String and character functions are used for the manipulation of strings and characters.

NAME DESCRIPTION
strcat(string1, string2) Concatenates string2 to string1.
strcmp(string1,string2) Compares string2 to string1. Returns 0 if the strings are equal. Returns < 0 if string1 < string2. Returns > 0 if string > string2.
strcpy(string1,string2) Copies string2 to string1
strlen(string1,string2) Returns the length of the string.
isalpha(character) Returns non-zero if the character is a letter; otherwise returns 0
isupper(character) Returns non-zero if the character is upper case, otherwise returns zero.
islower(character) Returns non-zero if the character is lower case; otherwise returns zero.
isdigit(character) Returns non-zero if character is a digit (0-9); otherwise returns zero
toupper(character) Returns the upper case equivalent if the character is lower case; otherwise it returns the character unchanged.
tolower(character) Returns the lower case equivalent if the character is upper case; otherwise it returns the character unchanged.

No comments:

Post a Comment