Course Content
C Tutorial
About Lesson

Strings in C (null-terminated character arrays)

In C programming, strings are represented as arrays of characters terminated by a null character (”). These null-terminated character arrays allow the manipulation and storage of textual data.

Declaration and Initialization

Strings in C can be declared and initialized in various ways:

char str1[] = "Hello, World!"; // Automatically sized based on the string length
char str2[20] = "C Programming"; // Explicitly defining the array size
char str3[] = {'H', 'i', ''}; // Initializing character by character

Manipulating Strings

C provides a set of functions from the <string.h> library to perform operations on strings. Some commonly used functions include:

strlen()

Calculates the length of a string by counting characters until the null terminator is encountered.

strcpy() and strncpy()

Copies one string to another. strcpy() copies until it encounters the null terminator, while strncpy() allows specifying the number of characters to copy.

strcat() and strncat()

Concatenates two strings. strcat() appends the content of one string to another, while strncat() appends a specified number of characters.

strcmp() and strncmp()

Compares two strings. strcmp() compares two strings lexicographically, while strncmp() allows comparison up to a specified number of characters.

Handling String Input

When receiving user input or reading strings from the standard input, scanf() and fgets() are commonly used functions. However, care should be taken to prevent buffer overflow while reading input.

Null Termination

The null terminator (”) at the end of a C string is crucial. It marks the string’s endpoint, allowing C functions to determine the string’s length and preventing unintended access beyond the allocated memory