Lesson 14·C Programming

Strings in C

Null-terminated character sequences, string I/O, and string.h library utilities

What is a String?

A string in C is a one-dimensional array of characters terminated by a special null character (\0). String literals are enclosed in double quotation marks as "string_literal".

Common operations on strings include calculating length, comparing two strings, copying, concatenating, converting case, and reversing.

String Memory Structure (Null Terminator \0)

When the C compiler assigns a string to a character array, it automatically appends a null character ('\0') at the end. Therefore, array size must be at least length + 1.

Memory representation of name = "TECHNO"
'T'
0 (1st)
'E'
1 (2nd)
'C'
2 (3rd)
'H'
3 (4th)
'N'
4 (5th)
'O'
5 (6th)
'\0'
6 (7th)

Reading and Writing Strings

Standard String Handling Functions (string.h)

The <string.h> header file defines standard string manipulation functions:

strlen(s)Returns the number of characters in string s (excluding \0)
strcpy(s1, s2)Copies source string s2 into destination buffer s1
strcat(s1, s2)Appends string s2 onto the end of string s1
strcmp(s1, s2)Compares two strings lexicographically
strlwr(s)Converts all uppercase characters in s to lowercase
strupr(s)Converts all lowercase characters in s to uppercase
strrev(s)Reverses the sequence of characters in string s
C Example
#include <stdio.h>
#include <string.h>

void main() {
    char str[50] = "Technoexam";

    printf("Original: %s\n", str);
    printf("Length: %lu\n", strlen(str));
    
    strupr(str);
    printf("Uppercase: %s\n", str);
    
    strlwr(str);
    printf("Lowercase: %s\n", str);
    
    strrev(str);
    printf("Reversed: %s\n", str);
}
Program Output
Original: Technoexam
Length: 10
Uppercase: TECHNOEXAM
Lowercase: technoexam
Reversed: maxeonhceT