Free Courses

String Functions in C

Learn about string functions in C.

Updated - 9 Jun 202210 mins readPublished : 1 Mar 2022
Published : 1 Mar 2022
quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

String Functions in C

Overview

Strings are an array of characters that terminate with a null character '\0'. The difference between a character array and a string is that, unlike the character array, the string ends with a null character. There are various built-in string functions in the C programming language.

Scope

This article will include-

  • Definition of string functions in C
  • Declaration of String
  • Working of string functions in C and examples

Introduction to C String Functions

We're often required to modify the strings and perform several operations on them according to our needs. If we want to get the length of the string, we could run a loop and calculate its length, but it is not the best way in case of complex problems. Hence, string functions are used to make our code efficient and straightforward as they are pre-written so we can use them directly.

The string handling functions are defined in the header file string.h. This header file must be included in the C program to use the string handling functions.

String Declaration

There are two ways to declare strings in C:

  1. The following example will create a string as "Scaler" where the last character must always be a null character. The size mentioned within the brackets is the maximum number of characters a string could hold, and it is mandatory to give the size of a string if we are not initializing it at the time of declaration.
char company[7] = {'S', 'C', 'A', 'L', 'E', 'R' , '\0'};

  1. In this method, we do not need to put the null character at the end of the string constant. The compiler automatically inserts the null character at the end of the string.
char company[] = "SCALER";


String Functions

The following are the string functions in C:

FunctionDescription
strlen()It returns the string's length.
strnlen()It returns the specified value if the value specified is less than the string length, otherwise the string length.
strcmp()It compares two strings and returns 0 if the strings are the same.
strncmp()It compares two strings only to n characters.
strcat()It concatenates two strings and returns the concatenated string.
strncat()It concatenates n characters of one string to another string.
strcpy()It copies one string into another.
strncpy()It copies the first n characters of one string into another.
strchr()It finds out the first occurrence of a given character in a string.
strrchr()It finds out the last occurrence of a given character in a string.
strstr()It finds out the first occurrence of a given string in a string.
strnstr()It finds out the first occurrence of a given string in a string where the search is limited to n characters.
strcasecmp()It compares two strings without sensitivity to the case.
strncasecmp()It compares n characters of one string to another without sensitivity to the case.

Examples of String Functions in C

Let's look at an example to understand how string functions work in C.

strlen()

Syntax

size_t strlen(const char *str)

size_t represents long unsigned int.

It takes a string (character array or character pointer) as input and writes the length of that string without including the end character '\0'.

Program Code

#include <stdio.h>
#include <string.h>

int main() {

  char string1[20] = "ScalerAcademy";
  printf("Length of string string1: %ld", strlen(string1));
  return 0;
}

Output

Length of string string1: 13

strnlen()

Syntax

size_t strnlen(const char *str, size_t maxlen)

size_t represents long unsigned int.

strnlen() take a string and a positive integer maxlen as input and return the length of the string if maxlen is greater than the size of the string otherwise, always return maxlen which means it only counts the characters till str[maxlen -1].

Program Code

#include <stdio.h>
#include <string.h>

int main() {

  char string1[20] = "ScalerAcademy";
  printf("Length of string string1 when maxlen is 25: %ld \n", strnlen(string1, 25));
  printf("Length of string string1 when maxlen is 5: %ld", strnlen(string1, 5));
}

Output

Length of string string1 when maxlen is 25: 13. 
Length of string string1 when maxlen is 5: 5

strcmp()

Syntax

int strcmp(const char *str1, const char *str2)

strcmp() takes two strings as input, then compares them, and returns an integer based on the following condition:

ExpressionReturns
string 1 > string 2Positive integer
string 1 < string 2Negative
string 1 = string 2Zero

Program Code

#include <stdio.h>
#include <string.h>

int main() {

  char s1[20] = "ScalerAcademy"; // string1
  char s2[20] = "ScalerAcademy.COM"; // string2
  // comparing both the strings
  if (strcmp(s1, s2) == 0) {
    printf("string 1 and string 2 are equal");
  } else {
    printf("string 1 and 2 are different");
  }
}

Output

string 1 and 2 are different

strncmp()

Syntax

int strncmp(const char *str1, const char *str2, size_t n)

size_t is for long unsigned int.

It compares only the first n characters of both the strings and returns an integer value accordingly:

ExpressionReturns
string 1(first n characters) > string 2(first n characters)Positive integer
string 1(first n characters) < string 2(first n characters)Negative
string 1(first n characters) = string 2(first n characters)Zero
Program Code
#include <stdio.h>
#include <string.h>

int main() {

  char s1[20] = "ScalerAcademy";
  char s2[20] = "ScalerAcademy.COM";
  /* it only compares first 5 characters of both strings*/
  if (strncmp(s1, s2, 5) == 0) {
    printf("string 1 and string 2 are equal");
  } else {
    printf("string 1 and 2 are different");
  }

}

Output

string 1 and string 2 are equal

strcat()

Syntax

char *strcat(char *str1, char *str2)

It takes two strings as input and concatenates the second string to the first string, which means it will attach the second string to the end of the first string and save the concatenated string to the first string. The size of the first string should be large enough to save the result.

Program Code

#include <stdio.h>
#include <string.h>

int main() {

  char string1[10] = "Hello";
  char string2[10] = "World";
  strcat(string1, string2);
  printf("Output string after concatenation: %s", string1);

}

Output

Output string after concatenation: HelloWorld

strncat()

Syntax

char *strncat(char *str1, char *str2, int n)

It takes two strings as input and attaches only the first n characters of the second string to the end of the first string.

Program Code

#include <stdio.h>
#include <string.h>

int main () {

     char string1[10] = "Hello";
     char string2[10] = "World";
     strncat(string1,string2, 3);
     printf("Concatenation using strncat: %s", string1);

     
}

Output

Concatenation using strncat: HelloWor

strcpy()

Syntax

char *strcpy( char *str1, char *str2)

It takes two strings as input and overwrites the data of the second string into the first string, i.e., it copies the data of the second string to the first string.

Program Code

#include <stdio.h>
#include <string.h>

int main() {

  char s1[35] = "string 1"; // string1
  char s2[35] = "I'll be copied to string 1."; // string2
  strcpy(s1, s2); // copying string2 to string1
  printf("String s1 is: %s", s1); // printing string1

}

Output

String s1 is: I'll be copied to string 1.

strncpy()

Syntax

char *strncpy( char *str1, char *str2, size_t n)

size_t is long unsigned int and n is an integer.

It takes two strings as input and overwrites the data of the first string by the second string based on specific conditions:

If the length of string2 is greater than n, it copies only the first n characters of string2 to string1; otherwise, it copies the entire string2 to string1.

Program Code

#include <stdio.h>
#include <string.h>

int main() {

  char string1[30] = "string 1";
  char string2[40] = "Only 12 characters will be copied.";
  strncpy(string1, string2, 12);
  printf("String s1 is: %s", string1);
}

Output

String s1 is: Only 12 char

strchr()

Syntax

char *strchr(char *str, int ch)

It takes a string and a character as input and finds out the first occurrence of the given character in that string. It will return the pointer to the first occurrence of that character; if found otherwise, return Null.

Program Code 1

  • When the character is present in the given string
#include <stdio.h>
#include <string.h>

int main() {

  char string1[30] = "I love to write.";
  printf("%s", strchr(string1, 'w'));
}

Output

write.

Program code 2

  • When the character is not present in the given string Notice the character 'z' is not present in the provided string. In such a case, it returns a null value.
#include <stdio.h>
#include <string.h>

int main() {

  char string1[30] = "I love to write blogs.";
  printf("%s", strrchr(string1, 'z'));
}

Output

(null)

strrchr()

Syntax

char *strrchr(char *str, int ch)

It takes a string and a character as input and finds out the last occurrence of a given character in that string. It will return the pointer to the last occurrence of that character if found otherwise, return Null.

Program Code 1

#include <stdio.h>
#include <string.h>

int main() {

  char string1[30] = "I love to write blogs.";
  printf("%s", strrchr(string1, 'w'));
}

Output

write blogs.

Program Code 2

  • When the character is not present in the given string Notice the character 'z' is not present in the provided string. In such a case, it returns a null value.
#include <stdio.h>
#include <string.h>

int main() {

  char string1[30] = "I love to write blogs.";
  printf("%s", strrchr(string1, 'z'));
}

Output

(null)

strstr()

Syntax

char *strstr(char *str, char *srch_term)

It takes two strings as input and finds out the first occurrence of the second string in the first string. It will return a pointer that points to the start of the first occurrence of the second string in the first string and a Null if the second string is not present in the first string.

Program Code

#include <stdio.h>
#include <string.h>

int main() {

  char string1[70] = "You are reading string functions.";
  printf("Output string is: %s", strstr(string1, "string"));
}

Output

Output string is: string functions.

strcasecmp()

Syntax

strcasecmp(str1, str2)

It takes two strings as input and compares them irrespective of their case sensitivity.

IfReturns
str1 < str2Less than 0
str1 = str2 (ignoring case)0
str1 > str2Greater than 0

Program Code

#include <stdio.h>
#include <string.h>

int main () {

  char string1[70] = "STRING";
  char string2[70]= "string";
  int result;

  result = strcasecmp(string1, string2);
  //checking the result using conditional statements.
  if (result == 0)
    printf("Strings are equal.\n");
    
  else if (result < 0)
    printf("\"%s\" is less than \"%s\".\n", string1, string2);
    
  else
    printf("\"%s\" is greater than \"%s\".\n", string1, string2);
}

Output

Strings are equal.

strncasecmp()

Syntax

strncasecmp(str1, str2, n)

It takes two strings as input and compares them till n characters irrespective of their case sensitivity. Program Code

#include <stdio.h>
#include <string.h>

int main() {

  char string1[70] = "STRING";
  char string2[70] = "steing";
  int result;

  result = strncasecmp(string1, string2, 3);
  //checking the result using conditional statements.

  if (result == 0)
    printf("Strings are equal.\n");

  else if (result < 0)
    printf("\"%s\" is less than \"%s\".\n", string1, string2);

  else
    printf("\"%s\" is greater than \"%s\".\n", string1, string2);
}

Output

"STRING" is greater than "steing".

Conclusion

  • By the end of the article, you will be familiar with string data type and its declaration in C.
  • Character arrays and strings are different in that a string ends with a null character, while character arrays do not.
  • The article covers C's various built-in string functions and their examples.
  • The string functions in C are easy to use and increase efficiency.
Challenge Time!
quiz
quiz
Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.
certificate icon
Certificates
C Tutorial
This program includes modules that cover the basics to advance constructs of C Tutorial. The highly interactive and curated modules are designed to help you become a master of this language.'
If you’re a learning enthusiast, this is for you.
Module Certificate
Criteria
Upon successful completion of all the modules in the hub, you will be eligible for a certificate.
You need to sign in, in the beginning, to track your progress and get your certificate.
Free Courses by top Scaler instructors