How can you access each character of a string in the C language?
In C language, you can access each character of a string by using an array. Each character can be accessed by its index, starting from 0.
The following is a sample code that demonstrates how to access each character of a string:
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
int i;
for(i = 0; str[i] != '\0'; i++) {
printf("%c ", str[i]);
}
return 0;
}
The output result is:
H e l l o , W o r l d !
In the example above, we used a for loop to iterate through the string `str`. The loop’s condition is `str[i] != ‘\0’`, meaning it will continue to execute until it reaches the end of the string (the null character ‘\0’). In each iteration, the `printf` function is used to print the character at the corresponding index `str[i]`.
It is important to note that in the C language, strings end with a null character ‘\0’, indicating the end of the string. Therefore, we can use ‘\0’ as a loop condition to determine if the string has ended.