C Programming/C String

Built-in function in C String

Updated on January 14, 2026
2 min read

To understand how <string.h> functions work, it is best to see them as pointer-based operations that navigate through memory until they find the null terminator (\0).

Here are the four essential string functions explained with separate examples.

1. strlen() — String Length

This function counts every character in the array until it hits the null terminator. It does not count the \0 itself.

c
1#include <stdio.h>
2#include <string.h>
3
4int main() {
5    char name[] = "Syntax";
6    size_t length = strlen(name);
7
8    printf("String: %s\n", name);
9    printf("Length: %zu\n", length); // Output: 6
10    return 0;
11}

2. strcpy() — String Copy

This function copies the contents of one memory location to another. It continues copying until it finds the \0 in the source string.

Note: The destination must be large enough to hold the incoming data.

c
1#include <stdio.h>
2#include <string.h>
3
4int main() {
5    char src[] = "C Programming";
6    char dest[20]; // Ensure this is large enough
7
8    strcpy(dest, src);
9
10    printf("Source: %s\n", src);
11    printf("Destination: %s\n", dest); 
12    return 0;
13}

3. strcat() — String Concatenation

This function "glues" two strings together. It finds the \0 of the first string and starts overwriting it with the first character of the second string.

c
1#include <stdio.h>
2#include <string.h>
3
4int main() {
5    char str1[50] = "Learn ";
6    char str2[] = "Syntax";
7
8    strcat(str1, str2);
9
10    printf("Result: %s\n", str1); // Output: Learn Syntax
11    return 0;
12}

4. strcmp() — String Comparison

This function compares two strings character by character by looking at their ASCII values.

  • Returns 0 if strings are identical.
  • Returns positive if the first mismatching character in the first string is greater.
  • Returns negative if it is smaller.
c
1#include <stdio.h>
2#include <string.h>
3
4int main() {
5    char s1[] = "Apple";
6    char s2[] = "Apple";
7    char s3[] = "Banana";
8
9    printf("Comparing s1 and s2: %d\n", strcmp(s1, s2)); // Output: 0 (Equal)
10    printf("Comparing s1 and s3: %d\n", strcmp(s1, s3)); // Output: Negative (A < B)
11
12    return 0;
13}

Summary Table

FunctionLogical ActionPointer Behavior
strlenCountSteps forward until *p == '\0'.
strcpyDuplicateCopies *src to *dest until \0 is reached.
strcatAppendMoves to end of dest, then starts copying src.
strcmpSubtractSubtracts ASCII values of characters at the same index.
Built-in function in C String | C Programming | Learn Syntax