Skip to main content

Accessing String elements in C

Accessing String elements

In C, you can access the individual elements of a string (i.e., characters) by using the array notation.

The syntax for accessing a character in a string is as follows:

string_name[index];

Here, string_name is the name of the string variable, and index is the zero-based index of the character you want to access.

For example:

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

You can access the first character of the string (i.e., 'H') as follows:

char first_char = greeting[0];

And you can access the second character (i.e., 'e') as follows:

char second_char = greeting[1];

Accessing String elements - Example

You can use a loop to access all the characters in a string and perform operations on them.

For example, the following code prints all the characters in the greeting string:

#include <stdio.h>

int main()
{
char greeting[20] = "Hello, World!";
int i;

for (i = 0; greeting[i] != '\0'; i++)
{
printf("%c", greeting[i]);
}
printf("\n");

return 0;
}
Output:

Explanation

  • The loop iterates through all the characters in the string until it reaches the null terminator ('\0').
  • The printf function is used to print each character in the string
  • A newline character ('\n') is printed after the last character to separate the output from the next line.