Skip to content

Introduction to Strings in C

Introduction

Strings in C are sequences of characters terminated by a null character (‘\0’). They are represented as arrays of characters, where each character corresponds to one element in the array. C does not have a built-in string data type like some higher-level languages; instead, strings are typically represented as arrays of characters.

Declaring Strings:

Strings in C can be declared using character arrays. The array size should be large enough to accommodate the string characters along with the null terminator.

char str1[10] = “Hello”; // Includes space for null terminator

char str2[] = “World”; // Compiler calculates size including null terminator

String Initialization:

Strings can be initialized using double quotes. When you initialize a string with a string literal, the compiler automatically adds the null terminator.

char greeting[] = “Hello, World!”;

String Input/Output:

You can use standard input/output functions like printf() and scanf() for string input and output.

printf(“String: %s\n”, str1); // Output string

scanf(“%s”, str2); // Input string

String Functions:

C provides several string manipulation functions in the standard library (<string.h>) for performing various operations on strings.

  • strlen(): Returns the length of the string.
  • strcpy(): Copies one string to another.
  • strcat(): Concatenates two strings.
  • strcmp(): Compares two strings.
  • strchr(): Finds the first occurrence of a character in a string.
  • strstr(): Finds the first occurrence of a substring in a string, etc.

#include <stdio.h>

#include <string.h>

int main() {

    char str1[20] = “Hello”;

    char str2[20] = “World”;

    printf(“Length of str1: %d\n”, strlen(str1)); // Output: 5

    printf(“Concatenated string: %s\n”, strcat(str1, str2)); // Output: HelloWorld

    return 0;

}

String Termination:

Strings in C are terminated by a null character (‘\0’). This null character indicates the end of the string and is used by string manipulation functions to determine the string’s length.

String Input/Output Functions:

In addition to printf() and scanf(), C provides specific input/output functions for strings, such as gets() and puts(). However, these functions are deprecated due to security vulnerabilities. Instead, it’s recommended to use fgets() for input and printf() for output.

Handling Strings in Functions:

When passing strings to functions, you typically pass them as pointers to the first character of the string. This allows functions to modify the string if necessary.

void modifyString(char *str) {

    strcat(str, ” World!”);

}

int main() {

    char greeting[20] = “Hello”;

    modifyString(greeting);

    printf(“%s\n”, greeting); // Output: Hello World!

    return 0;

}

Understanding how strings work in C, along with the standard string manipulation functions, is essential for working with text-based data and implementing various algorithms and programs.