Labs ICT
⭐ Pro Login

String Functions

2 min read | C Tutorial
⭐

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Manipulating strings character by character is tedious. The string.h header gives you handy functions for the most common tasks — measuring length, copying, joining, and comparing.

strlen — String Length

strlen returns the number of characters in a string, not counting the null terminator.


#include <stdio.h>
#include <string.h>
int main() {
  char msg[] = "Hello";
  int len = strlen(msg);
  printf("Length: %d\n", len);
  return 0;
}
    

strcpy — Copy a String

strcpy copies from source to destination. Make sure the destination is big enough to hold the entire string including the null terminator.


#include <stdio.h>
#include <string.h>
int main() {
  char src[] = "Copied!";
  char dest[20];
  strcpy(dest, src);
  printf("Destination: %s\n", dest);
  return 0;
}
    

strcat — Concatenate Strings

strcat appends one string to the end of another. The destination must be large enough to hold the result.


#include <stdio.h>
#include <string.h>
int main() {
  char str1[20] = "Hello ";
  char str2[] = "World";
  strcat(str1, str2);
  printf("%s\n", str1);
  return 0;
}
    

strcmp — Compare Strings

strcmp compares two strings character by character. It returns 0 if they're equal, negative if the first is smaller, positive if the first is larger.


#include <stdio.h>
#include <string.h>
int main() {
  char pass[] = "secret";
  char input[] = "secret";
  if (strcmp(input, pass) == 0) {
    printf("Access granted\n");
  } else {
    printf("Access denied\n");
  }
  return 0;
}