C documentation V1 Help

Character Strings Overview

Introduction

In C programming, character strings are sequences of characters stored in contiguous memory locations. Unlike some high-level languages, C does not have a built-in string type; instead, strings are represented as arrays of characters. Let's explore the fundamental concepts related to character strings in C.

Declaration of Character Strings

Character strings in C are typically declared as arrays of characters. The array size should be large enough to accommodate the string characters along with the null character ('\0'), which marks the end of the string.

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // or char greeting[] = "Hello";

The second declaration automatically calculates the size based on the number of characters in the string plus one for the null character.

String Initialization

Strings can be initialized at the time of declaration or later using various methods.

char message[] = "Welcome"; // or char message[8]; strcpy(message, "Welcome");

Here, strcpy is a string copy function from the <string.h> library.

String Input and Output

C provides functions for reading and displaying strings:

char name[20]; printf("Enter your name: "); scanf("%19s", name); // Read a string (limiting to 19 characters to leave space for null character) printf("Hello, %s!\n", name); // Display the string

String Functions

C provides a set of standard library functions for string manipulation. Some commonly used functions include:

  • strlen: Calculates the length of a string.

  • strcpy: Copies one string to another.

  • strcat: Concatenates two strings.

  • strcmp: Compares two strings.

#include <string.h> char str1[20] = "Hello"; char str2[] = "World"; int length = strlen(str1); strcpy(str1, "Bonjour"); strcat(str1, " "); strcat(str1, str2); int comparison = strcmp(str1, str2);

Character Array vs. String

In C, a character array and a string are often used interchangeably. However, it's essential to remember that a character array becomes a string when null-terminated.

char arr[] = {'H', 'e', 'l', 'l', 'o'}; // Not a string char str[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // String

Conclusion

Character strings play a crucial role in C programming for representing and manipulating text data. Understanding the array-based representation and utilizing string functions contribute to effective string handling in C.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!

Last modified: 25 February 2024