In C, a string is a sequence of characters stored in an array. Unlike some other programming languages, C does not have a built-in string data type. Instead, strings are represented as arrays of characters terminated by a special null character '\0'
.
A string in C is essentially a character array. Here's the syntax for declaring a string:
char str[50]; // Declaring a string (character array) of size 50
You can initialize a string at the time of declaration:
char str[] = "Hello, World!";
Here's an example of how to declare, initialize, and print a string in C:
#includeint main() { char str[] = "Hello, C Programming!"; // String initialization // Printing the string printf("%s\n", str); // Output: Hello, C Programming! return 0; }
str
is initialized with "Hello, C Programming!" and printed using printf
with the format specifier %s
, which is used for strings.
In C, you can calculate the length of a string using the strlen()
function from the string.h
library:
#include#include // Including string.h for strlen() int main() { char str[] = "Hello"; int length = strlen(str); // Finding the length of the string printf("Length of string: %d\n", length); // Output: 5 return 0; }
strlen()
function returns the number of characters in the string excluding the null character ('\0'). For the string "Hello", the length is 5.
C provides several functions to manipulate strings. Here are a few commonly used ones:
Hereโs an example demonstrating strcpy()
and strcat()
:
#include#include int main() { char str1[20] = "Hello, "; // Destination string char str2[] = "World!"; // Source string // Using strcpy to copy str2 to str1 strcpy(str1, str2); printf("After copying: %s\n", str1); // Output: World! // Concatenating str1 and str2 strcat(str1, " C Programming"); printf("After concatenation: %s\n", str1); // Output: World! C Programming return 0; }
strcpy()
copies the content of str2
into str1
, and strcat()
concatenates the strings, adding " C Programming" to the end of str1
.
'\0'
.malloc
and free
.'\0'
at the end can lead to undefined behavior.Strings are essential in programming and are often used for handling text input, output, and manipulation. Understanding how to work with strings and their functions will significantly enhance your ability to handle textual data in C. Remember, though, strings in C are arrays of characters, so always be mindful of the memory allocated for them!
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!