String
A string in C is a sequence of characters stored in an array and terminated with a null character ('\0'). Strings are used to represent text data in C, and they are often used for input and output operations.
In C, strings are represented as arrays of characters, and they are manipulated using string-handling functions provided in the standard library.
Here is an example of declaring and initializing a string in C:
#include <stdio.h>
int main()
{
char str[10] = "hello";
return 0;
}
In this example, we have declared a string str as an array of characters with a size of 10. The string is initialized with the value "hello", which is stored in the array along with a null character at the end to mark the end of the string.
You can access individual characters of a string using the index operator []. The index of a character in a string starts at 0 and goes up to the length of the string minus 1. For example:
#include <stdio.h>
int main()
{
char str[10] = "hello";
printf("str[0] = %c\n", str[0]); // prints 'h'
printf("str[1] = %c\n", str[1]); // prints 'e'
printf("str[2] = %c\n", str[2]); // prints 'l'
printf("str[3] = %c\n", str[3]); // prints 'l'
printf("str[4] = %c\n", str[4]); // prints 'o'
return 0;
}
In this example, we have accessed each character of the string str and printed its value to the console.
You can also use a loop to iterate over the characters of a string. For example:
#include <stdio.h>
int main()
{
char str[10] = "hello";
for (int i = 0; str[i] != '\0'; i++) {
printf("str[%d] = %c\n", i, str[i]);
}
return 0;
}
In this example, we have used a for loop to iterate over the characters of the string str. The loop continues to iterate as long as the current character is not the null character, which indicates the end of the string.