C strings
Strings are used to storing text, C strings are arrays of characters in the C programming language used to represent text. In this article, we will take a closer look at different aspects of C strings, including initialization, declaration, assignment, fixed length strings, and array strings.
Initialization of C Strings
A C string can be initialized in two ways in C programming: using a string literal or by declaring an array of characters. When using a string literal, the string is assigned to an array of characters and the null character ('\0') is automatically added at the end of the string to mark its end.
Here's an example of initializing a string using a string literal:
1char string1[] = "Hello, World!";
Declaration of C Strings
A C string can also be declared by specifying the size of the array and then assigning the characters to the array. For example:
1char string2[15];
In this example, the string string2
is declared as an array of 15 characters. Note that the size of the string must include space for the null character ('\0') at the end.
Assignment of C Strings
Once a C string is declared, you can assign characters to it using the strcpy()
function from the string.h
library. This function takes two parameters, the destination string and the source string, and copies the contents of the source string to the destination string.
Here's an example of assigning characters to a C string:
1#include <stdio.h> 2#include <string.h> 3 4int main() { 5 char string2[15]; 6 strcpy(string2, "Hello, World!"); 7 printf("%s\n", string2); 8 return 0; 9}
Fixed Length Strings
In C programming, you can specify the length of a string by declaring an array of characters with a fixed size. For example:
1char string3[15] = "Hello, World!";
In this example, the string string3
is declared as an array of 15 characters and is initialized with the string "Hello, World!". Note that the size of the string must include space for the null character ('\0') at the end.
Array Strings
In C programming, you can create an array of strings by declaring an array of arrays of characters. For example:
1char string4[][15] = {"Hello, World!", "Goodbye, World!", "See you later, World!"};
In this example, the array string4
is declared as an array of three strings, each of which is an array of 15 characters.