String Basics in C

Posted on November 13, 2023 by Vishesh Namdev
Python C C++ Java
C Programming Language

String is a sequence of characters represented as an array of characters, terminated by a null character '\0'. C does not have a built-in string data type like some other programming languages, such as C++ or Java. Instead, strings are typically represented as arrays of characters.

String in C

Declaring a string:

Declaring a string in C involves defining a character array that will hold the sequence of characters that make up the string.

char myString[50];

In this example, we've declared a character array called myString that can hold up to 50 characters. This array can be used to store a string of characters, and you can access and manipulate individual characters within this array.

char greeting[] = " Hello, World! ";

In this case, C will automatically determine the size of the array based on the length of the provided string and add a null character at the end to terminate the string. This is a common way to declare and initialize strings in C.

Initializing a string

Initializing a string in C involves assigning an initial value to a character array, which is used to represent the string. You can initialize a string in C in several ways:

(a) Initializing during declaration:

char greeting[] = " Hello, World! ";

(b) Initializing character by character:

char greeting[13]; // Declare an array of 13 characters
greeting[0] = 'H';
greeting[1] = 'e';
greeting[2] = 'l';
greeting[3] = 'l';
greeting[4] = 'o';
greeting[5] = ',';
greeting[6] = ' ';
greeting[7] = 'W';
greeting[8] = 'o';
greeting[9] = 'r';
greeting[10] = 'l';
greeting[11] = 'd';
greeting[12] = '\0'; // Null-terminate the string

(c) Using string library functions:

#include <string.h>

char destination[20];
char source[] = "Hello, World!";
strcpy(destination, source); // Copies the source string into the destination array

In this example, we calculate the size of myArray using the sizeof operator and pass both the array and its size to the printArray function.

Accessing Elements from string

Accessing and modifying characters in a string in C involves using array indexing. Strings in C are represented as arrays of characters, and you can access individual characters in the array using their index.:

Example for Accessing characters
#include<stdio.h>Copy Code

int main() {
    char myString[] = "Hello, World!";

    // Accessing characters
    char firstChar = myString[0];
    char fifthChar = myString[4];

    // Printing characters
    printf("Fifth character: %c\n", firstChar);
    printf("Fifth character: %c\n", fifthChar);

    return 0;

In this example, myString[0] accesses the first character ('H'), and myString[4] accesses the fifth character (','), using zero-based indexing.