C - Strings
Strings are represented as arrays of characters. Each character in the string is stored in a consecutive memory location, and a null character ('\0') marks the end of the string.
Accessing Strings:
You can access individual characters of a string using array indexing. The index starts from 0 for the first character and goes up to length - 1, where length is the number of characters in the string.
char str[] = "Hello";
char firstChar = str[0]; // Access the first character 'H'
char thirdChar = str[2]; // Access the third character 'l'
In this example, firstChar will have the value 'H', and thirdChar will have the value 'l'.
Modifying Strings:
In C, individual characters of a string can be modified just like any other array element.
char str[] = "Hello";
str[1] = 'a'; // Change the second character to 'a'
In this example, the second character of the string 'e' is changed to 'a', resulting in the string "Hallo".
Looping through a String:
You can use loops, such as the for loop, to iterate through the characters of a string.
char str[] = "Hello";
int length = strlen(str);
for (int i = 0; i < length; i++)
{
printf("%c ", str[i]); // Print each character of the string
}
In this example, the for loop is used to iterate through each character of the string str and print it.
Strings in C are represented as character arrays, and you can use array indexing to access and modify individual characters. Looping through a string allows you to perform operations on each character or process the string as a whole.