Strings

What Are Strings in C?

In C, strings are just arrays of characters that end with a special character called the null terminator ('\0').

char str[] = "Hello";  // Automatically adds '\0' at the endCopyEdit


Common String Functions (from <string.h>)

Function

Purpose

strcpy()

Copy one string into another

strcat()

Concatenate (join) two strings

strlen()

Get the length of a string

strcmp()

Compare two strings

strchr()

Find first occurrence of a char

strstr()

Find a substring in a string


strcpy(destination, source)

Copies the source string into the destination.

char src[] = "world"; char dest[10]; strcpy(dest, src);  
// dest now contains "world" 

Make sure dest has enough space!


strcat(destination, source)

Appends source to the end of destination.


char greeting[20] = "Hello "; char name[] = "Alice"; strcat(greeting, name);  // greeting becomes "Hello Alice"


strlen(str)

Returns the length of the string (excluding '\0).

char name[] = "Bob"; int len = strlen(name);  // len = 3


strcmp(str1, str2)

Compares two strings.

  • Returns 0 if equal

  • Returns a positive or negative value if not equal

strcmp("apple", "banana");  // returns negative strcmp("hello", "hello");   // returns 0 


strchr(str, ch)

Finds first occurrence of a character.

char *pos = strchr("hello", 'l');  // Points to first 'l'


strstr(str, substr)

Finds the first occurrence of a substring.

char *sub = strstr("I love C programming", "C");  // Points to "C programming" 


What About sprintf()?

sprintf() lets you format a string into a character array, just like printf() formats text on screen.

char buffer[100]; int age = 21; sprintf(buffer, "I am %d years old", age); puts(buffer);  // Outputs: I am 21 years old 

Use snprintf() instead to avoid buffer overflow by specifying max size.


Example: Full Use of String Functions

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

int main() {
    char name[50], greeting[100];
    printf("Enter your name: ");
    scanf("%s", name);

    strcpy(greeting, "Hello, ");
    strcat(greeting, name);

    printf("%s!\n", greeting);
    printf("Length of name: %lu\n", strlen(name));

    if (strcmp(name, "Alice") == 0) {
        printf("Nice to see you again!\n");
    }

    return 0;
}