C String Functions

The header file string.h has ready functions to work with strings. We must include it to use them.

Common string functions

FunctionWork
strlen(s)Returns the length of the string
strcpy(dest, src)Copies src to dest
strncpy(dest, src, n)Copies at most n characters
strcat(dest, src)Joins src at the end of dest
strncat(dest, src, n)Joins at most n characters
strcmp(a, b)Compares two strings
strncmp(a, b, n)Compares first n characters
strchr(s, c)Finds the first place of a character
strstr(s, sub)Finds a smaller string inside a string

Example

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

int main(void) {
    char a[30] = "Hello";
    char b[] = " World";

    strcat(a, b);
    printf("%s\n", a);
    printf("Length: %zu\n", strlen(a));
    printf("Compare: %d\n", strcmp("apple", "apple"));
    return 0;
}

Output:

Output of the above program is

Hello World
Length: 11
Compare: 0

Read each function in detail:

Note: These functions do not check if the destination has enough space. You must make the array big enough, or use the n versions.

Next: C strlen() Function.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a C program to find the sum and average of array elements
Write a C program to find the largest element in an array
Write a C program to print the elements of an array in reverse order
Write a C program to sort an array using bubble sort
Write a C program to search an element in an array
Write a C program to add two matrices
Write a C program to find the length of a string without using strlen
Interview Questions & Answers
What is an array in C?
How is a string stored in C?
How to reverse a string in C?
What is the difference between memcpy() and strcpy() in C?