๐งต Strings in C Language
๐น What is a String in C?A string in C is a sequence of characters stored in contiguous memory locations and terminated by a null character (\0).
๐ In C, strings are essentially arrays of characters.
โ Why Use Strings?
- Store text data like names, addresses, messages
- Perform operations like comparison and concatenation
- Essential for input/output operations
๐ String Declaration and Initialization
1๏ธโฃ Using Character Array
char name[20];
char name[20] = "Rahul";
2๏ธโฃ Using Pointer
char *name = "Rahul";
โ ๏ธ Important Notes
- Strings must end with \0
- String literals are read-only
- Array-based strings can be modified
๐ String Input and Output
#include <stdio.h>
int main() {
char name[20];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello %s", name);
return 0;
}
๐ For input with spaces, use: fgets(name, 20, stdin);
๐ Types of Strings in C
1๏ธโฃ Single-Dimensional String
char str[20] = "Hello";
#include <stdio.h>
int main() {
char str[10] = "C Language";
printf("%s", str);
return 0;
}
2๏ธโฃ String Using Pointer
char *str = "Hello World";
Pointer strings are stored in read-only memory. Modifying them causes undefined behavior.
3๏ธโฃ Array of Strings (2D Character Array)
#include <stdio.h>
int main() {
char names[3][10] = {"Amit", "Neha", "Ravi"};
for(int i = 0; i < 3; i++) {
printf("%s\n", names[i]);
}
return 0;
}
names[3][10] โ 3 strings, each with 9 characters + null terminator
4๏ธโฃ Pointer Array of Strings
#include <stdio.h>
int main() {
char *names[] = {"Amit", "Neha", "Ravi"};
for(int i = 0; i < 3; i++) {
printf("%s\n", names[i]);
}
return 0;
}
โ More memory-efficient than 2D arrays
๐ Common String Functions (<string.h>)
| Function | Description |
|---|---|
| strlen(str) | Returns length of string |
| strcpy(dest, src) | Copies src to dest |
| strcat(dest, src) | Concatenates strings |
| strcmp(str1, str2) | Compares two strings |
| strchr(str, ch) | Finds character |
| strstr(str, sub) | Finds substring |
๐ Example: strlen() and strcpy()
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20];
printf("Length: %lu\n", strlen(str1));
strcpy(str2, str1);
printf("Copied: %s", str2);
return 0;
}
๐ FAQs on Strings in C
Q1. What is a string in C?
A sequence of characters terminated by \0.
Q2. How to declare a string?
Using char array or pointer.
Q3. Can we modify string literals?
No, it causes undefined behavior.
Q4. Difference between 2D array and pointer array?
2D arrays store actual data, pointer arrays store addresses.
Q5. How is string length calculated?
Using strlen(), excluding \0.
๐ Key Points to Remember
- Strings are character arrays
- Always end with \0
- Use fgets for multi-word input
- Use <string.h> functions