Labs ICT
Pro Login

String Functions

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 
#include 
int main() {
  char msg[] = "Hello";
  int len = strlen(msg);
  printf("Length: %d\n", len);
  return 0;
}
    
Try it Yourself →

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 
#include 
int main() {
  char src[] = "Copied!";
  char dest[20];
  strcpy(dest, src);
  printf("Destination: %s\n", dest);
  return 0;
}
    
Try it Yourself →

strcat — Concatenate Strings

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


#include 
#include 
int main() {
  char str1[20] = "Hello ";
  char str2[] = "World";
  strcat(str1, str2);
  printf("%s\n", str1);
  return 0;
}
    
Try it Yourself →

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 
#include 
int main() {
  char pass[] = "secret";
  char input[] = "secret";
  if (strcmp(input, pass) == 0) {
    printf("Access granted\n");
  } else {
    printf("Access denied\n");
  }
  return 0;
}
    
Try it Yourself →