String Handling Functions

05 min read

String Handling Functions: Include <string.h> to use these functions.

1) String Length:

Syntax:  strlen(string);

  • This function returns the length of the string.
  • A string constant or an array of characters can be passed as an argument.
  • The length of the string excluded the end-of-string (NULL) character.

Example: 

char namen="James";
printf("%d",strlen(name));   //output: 5 as it doesn't take the '\0' character into account.


2) String Copy: Copies the contents of one string to another, i.e the source string is copied into the destination string.

 Syntax:  strcpy(destination_string, source_string);

Example:

char name1[]= "James", name2[10];
strcpy(name2,namel)
puts(name2);          // Output: James

 

3) String Compare

a) strcmp(): The strcmp() function compares two strings, character by character (the ASCII values of characters are compared) and returns an integer, whose value is

  • -1 if the first string is less than the second
  • 0 if both are identical
  • 1 if the first string is greater than the second

Syntax: strcmp(stringl, string2);

Example:

char name1[]="James", name2[]="James";
if((strcmp(name 1 ,name2)==0)
printf("Both strings are identical");   // Output: Both strings are identical

 

b) strncmp(): To compare only the 1st 'n' characters of the two strings.

Syntax: stmcmp(stringl, string2,n);

Example:

int status; 
char s1[]="India", s2[]="Indonesia";
status=strncmp(sl,s2,3);
printf(" %d",status);    //Output: 0 (because 1st three char's are identical in both)

 

c) stricmp():  This function performs a case-insensitive comparison of both the strings. i.e., lowercase and uppercase letters will be treated the same.

Syntax: stricmp(stringl, string2);

Example: 

int status;
char s1[]="India", s2[]="INDIA",
status=stricmp(s1,s2);
printf(' %d",status);           // Output: 0

 

d) strnicmp(): This function performs a case-insensitive comparison of both the strings only up to 'n' characters.

Syntax: strnicmp(stringl, string2, n);

 

4) strrev(): This function reverses the string.

Syntax: strrev(string);

 

5) strcat(): Concatenates the contents of one string to another, i.e the source string is concatenated to the end of the destination string.

Syntax: strcat(destination_string, source string);

 

6) strlen(): The function takes a single argument, i.e, the string variable whose length is to be found, and returns the length of the string passed.

Syntax: strlen(string_name);

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error