What is strcoll() Function in C language?

CServer Side ProgrammingProgramming

The C library function int strcoll(const char *str1, const char *str2) compares string str1 to str2. The result is dependent on the LC_COLLATE setting of the location.

An array of characters is called a string

Declaration

Given below is the declaration of an array −

char stringname [size];

For example − char string[50]; string of length 50 characters

Initialization

  • Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • Using string constants −
char string[10] = "Hello":;

Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’

The Strcoll() Function

This function is same as strcmp() function, it compares two strings and returns an integer based on the value of comparison.

Declaration

Given below is the declaration of strcoll() function −

int strcoll(const char *string1, const char *string2)

Here,

  • string1 refers to First String.
  • string2 refers to Second String.

Return value of strcoll()

  • > 0 when ASCII value of first unmatched char in string string1 is greater than string2.

  • < when ASCII value of first unmatched char in string string1 is less than string2.

  • =0 if both strings are equal.

Example

The following example shows the usage of strcoll() function.

 Live Demo

#include <stdio.h>
#include <string.h>
int main () {
   char string1[20];
   char string2[20];
   int final;
   strcpy(string1, "WELCOME");
   strcpy(string2, "Welcome to the world!");
   final = strcoll(string1, string2);
   if(final > 0){
      printf(" string1 is greater than string2");
   } else if(final < 0) {
      printf("string1 is less than string2");
   } else {
      printf("string1 and string2 are equal");
   }
   return 0;
}

Output

When the above program is executed, it produces the following result −

string1 is less than string2

Example

Let’s see another program.

Following is the program for comparing two strings using strcoll at runtime −

 Live Demo

#include <stdio.h>
int main (){
   char string1[20];
   char string2[20];
   int final;
   printf("enter string1:\n");
   gets(string1);
   printf("enter string2:\n");
   gets(string2);
   final = strcoll(string1, string2);
   if(final > 0){
      printf(" string1 is greater than string2");
   }
   else if(final < 0){
      printf("string1 is less than string2");
   }
   else{
      printf("string1 and string2 are equal");
   }
   return 0;
}

Output

When the above program is executed, it produces the following result −

enter string1:
Tutorails Point
enter string2:
Point
string1 is greater than string2
raja
Published on 11-Mar-2021 13:31:46
Advertisements