C Strings

C Strings: Working with Text

In C programming, a string is essentially a sequence of characters, such as "Hello World!". Unlike some other programming languages that have a dedicated string data type, C represents strings as arrays of characters.

The most crucial aspect of C strings is that they are null-terminated. This means a special character, the null character (\0), marks the end of the string. This null terminator is vital because it tells C functions where the string ends.


1. Declaring and Initializing Strings

You can declare and initialize strings in a few ways:

a. Character Array Initialization

Declare a character array and initialize it with a string literal. The compiler automatically adds the null terminator.

Character Array String Example

#include <stdio.h>

int main() { char greeting[6] = "Hello"; // An array of 6 characters (5 for "Hello" + 1 for '\0') printf("%s\n", greeting); return 0; }

You can also omit the size, and the compiler will calculate it:

Implicit Sizing Example

#include <stdio.h>

int main() { char city[] = "New York"; // Compiler determines size needed (8 for "New York" + 1 for '\0') printf("%s\n", city); return 0; }

b. Pointer to a String Literal

You can also declare a pointer to a string literal. String literals are stored in read-only memory.

String Literal Pointer Example

#include <stdio.h>

int main() { char *name = "Alice"; // 'name' points to the string literal "Alice" printf("%s\n", name); return 0; }

Important Note: When using char *name = "Alice";, you are creating a pointer to a string literal, which is usually stored in read-only memory. Modifying such a string (e.g., name[0] = 'B';) leads to undefined behavior and often a crash. For modifiable strings, always use character arrays.


2. String Length (strlen)

The strlen() function, found in the <string.h> header, calculates the length of a string, excluding the null terminator.

Syntax:

size_t strlen(const char *str);

strlen() Example

#include <stdio.h>
#include <string.h> // Required for strlen()

int main() { char text[] = "Programming"; printf("Length of "%s" is %lu\n", text, strlen(text)); // %lu for size_t return 0; }


3. Copying Strings (strcpy, strncpy)

You cannot assign one character array to another directly using the = operator. Instead, you use strcpy() or strncpy().

strcpy(destination, source): Copies the source string to the destination. Be cautious, as it doesn't check buffer size and can lead to buffer overflows if destination is too small.

strncpy(destination, source, num): Copies at most num characters from source to destination. This is safer but requires careful handling of null termination if source is longer than num.

strcpy() and strncpy() Example

#include <stdio.h>
#include <string.h> // Required for strcpy() and strncpy()

int main() { char original[] = "Hello World"; char copy[20]; // Make sure destination has enough space char partialCopy[5];

strcpy(copy, original); printf("Copied string: %s\n", copy);

strncpy(partialCopy, original, 4); // Copy first 4 characters partialCopy[4] = '\0'; // Manually null-terminate if source is longer than count printf("Partially copied string: %s\n", partialCopy);

return 0; }


4. Concatenating Strings (strcat, strncat)

The strcat() function appends one string to the end of another.

strcat(destination, source): Appends source to destination. Again, beware of buffer overflows.

strncat(destination, source, num): Appends at most num characters from source to destination. Safer, but still ensure destination has sufficient capacity.

strcat() and strncat() Example

#include <stdio.h>
#include <string.h> // Required for strcat() and strncat()

int main() { char firstName[20] = "John"; char lastName[] = " Doe"; char buffer[50] = "First Part"; char secondPart[] = " and Second Part";

strcat(firstName, lastName); // firstName now holds "John Doe" printf("Full Name: %s\n", firstName);

strncat(buffer, secondPart, 5); // Appends " and " printf("Concatenated buffer: %s\n", buffer);

return 0; }


5. Comparing Strings (strcmp, strncmp)

To compare two strings, you cannot use == because that would compare their memory addresses, not their content. Use strcmp() or strncmp().

strcmp(str1, str2): Compares str1 and str2 lexicographically.

strncmp(str1, str2, num): Compares at most the first num characters of str1 and str2. The return values follow the same rules as strcmp().

strcmp() and strncmp() Example

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

int main() { char str1[] = "Apple"; char str2[] = "App";

if (strcmp(str1, str2) == 0) { printf("Strings are completely equal.\n"); } else { printf("Strings are different.\n"); }

if (strncmp(str1, str2, 3) == 0) { printf("First 3 characters are equal.\n"); }

return 0; }


Exercise

?

Which function is used to safely copy a specific number of characters from one string to another?