Strings in C programming language
Here’s a clean, beginner-friendly blog you can use on Strings in C:
๐งต Strings in C: A Complete Beginner’s Guide
Strings are one of the most important concepts in C programming. Whether you're working with user input, text processing, or file handling, understanding strings is essential.
๐ค What is a String in C?
In C, a string is an array of characters terminated by a special character called the null character ('\0').
Example:
char name[] = "Hello";
This is stored in memory as:
H e l l o \0
๐ฆ Declaring and Initializing Strings
1. Using Character Array
char str[10] = "Hello";
2. Without Size (Auto-sized)
char str[] = "World";
3. Character by Character
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
๐ฅ Taking String Input
Using scanf()
scanf("%s", str);
⚠️ Stops reading at whitespace.
Using gets() (Not Recommended ❌)
gets(str);
Unsafe because it can cause buffer overflow.
Using fgets() (Recommended ✅)
fgets(str, sizeof(str), stdin);
๐ค Printing Strings
printf("%s", str);
๐งฐ Common String Functions
C provides built-in string functions in the header file:
#include <string.h>
1. strlen()
Finds length of string
strlen(str);
2. strcpy()
Copies one string to another
strcpy(dest, src);
3. strcat()
Concatenates (joins) two strings
strcat(str1, str2);
4. strcmp()
Compares two strings
strcmp(str1, str2);
๐ Looping Through a String
for(int i = 0; str[i] != '\0'; i++) {
printf("%c", str[i]);
}
⚠️ Common Mistakes
❌ Forgetting the null character
'\0'❌ Using
gets()(unsafe)❌ Not allocating enough memory
❌ Modifying string literals (undefined behavior)
๐ฏ Tips & Best Practices
Always use
fgets()instead ofgets()Check string length before operations
Use
sizeof()to avoid overflowPrefer standard library functions
Comments
Post a Comment