Introduction to Strings in C
Strings in C are a sequence of characters terminated by a null character (\0
). Unlike other programming languages, C does not have a built-in string data type, so strings are implemented using character arrays. Understanding strings is crucial for tasks such as user input handling, file processing, and text manipulation.
What are Strings in C?
In C, a string is an array of characters terminated by a special null character \0
. This null terminator plays a vital role in indicating the end of the string.

Memory Representation of Strings
A string "Hello"
in memory looks like this:
| H | e | l | l | o | \0 |
The null terminator ensures that functions like printf
and strlen
can determine the string’s length dynamically at runtime.
Key Concepts of Strings in C
- Character Array: Strings in C are stored as arrays of characters with the last element being
\0
. - Null Terminator: Indicates the end of the string. Without it, the program might read unintended memory.
- Standard Library: The
<string.h>
library provides various string manipulation functions.
Declaring and Initializing Strings
Method 1: Static Declaration
char str[20] = "Hello, C!";
- Allocates a fixed size of 20 characters.
- Allows modifying individual characters within the allocated memory.
Method 2: Dynamic Declaration (Using Pointers)
char* str = "Hello, World!";
- Allocates memory dynamically.
- The string is stored in read-only memory, meaning you cannot modify the contents.
Input and Output Operations
Handling input and output is essential for processing user data in strings.
Using scanf()
for Input
#include <stdio.h> int main() { char name[50]; printf("Enter your name: "); scanf("%s", name); printf("Hello, %s!\n", name); return 0; }
scanf()
stops reading input at spaces, making it unsuitable for multi-word strings.- Clickme!
Using fgets()
for Multi-Word Strings
#include <stdio.h> int main() { char name[50]; printf("Enter your full name: "); fgets(name, sizeof(name), stdin); printf("Hello, %s", name); return 0; }
- Advantage: Reads the entire line, including spaces.
- Note:
fgets()
includes the newline character\n
. - Clickme!
Strings in C Operations
C provides a robust set of functions in <string.h>
for performing string operations.
1. strlen()
– Calculate String Length
#include <string.h> int length = strlen("Hello");
2. strcpy()
– Copy Strings
char dest[20]; strcpy(dest, "Source");
3. strcat()
– Concatenate Strings
char str1[20] = "Hello, "; char str2[] = "World!"; strcat(str1, str2);
4. strcmp()
– Comparing Strings
if (strcmp("abc", "abc") == 0) { printf("Strings are equal"); }
- Returns
0
if strings are equal. - Returns
< 0
if the first string is lexicographically smaller. - Returns
> 0
if the first string is lexicographically greater.
5. strchr()
and strrchr()
– Find Characters
strchr()
finds the first occurrence of a character.strrchr()
finds the last occurrence.
char* pos = strchr("Hello, World!", 'W');
6. strstr()
– Find Substrings
char* found = strstr("Hello, World!", "World");
Best Practices for Working with Strings in C
- Allocate Sufficient Memory: Ensure arrays are large enough to hold strings and the null terminator.
- Avoid Buffer Overflows: Validate input lengths to prevent memory corruption.
- Prefer
fgets()
overscanf()
: For safe input handling. - Use Standard Functions: Leverage
<string.h>
functions for efficiency and readability.
Common Operations with Examples in Strings in C
1. Reversing a String
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello"; int n = strlen(str); for (int i = 0; i < n / 2; i++) { char temp = str[i]; str[i] = str[n - i - 1]; str[n - i - 1] = temp; } printf("Reversed: %s\n", str); return 0; }
2.Counting Vowels and Consonants
#include <stdio.h> #include <ctype.h> int main() { char str[] = "Hello, World!"; int vowels = 0, consonants = 0; for (int i = 0; str[i] != '\0'; i++) { char ch = tolower(str[i]); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels++; else if (isalpha(ch)) consonants++; } printf("Vowels: %d, Consonants: %d\n", vowels, consonants); return 0; }
3.Checking Palindrome Strings
#include <stdio.h> #include <string.h> int main() { char str[] = "madam"; int n = strlen(str), isPalindrome = 1; for (int i = 0; i < n / 2; i++) { if (str[i] != str[n - i - 1]) { isPalindrome = 0; break; } } if (isPalindrome) printf("Palindrome\n"); else printf("Not a Palindrome\n"); return 0; }
Advantages and Challenges of Strings in C
Advantages:
- Efficient memory usage.
- Fine-grained control over character arrays.
- Compatibility with various data formats.
Challenges:
- Manual memory management.
- Risk of buffer overflows.
- Limited abstraction compared to higher-level languages.
Conclusion
Strings in C are powerful yet demand careful handling due to their low-level implementation. By mastering the concepts, functions, and best practices outlined here, you can work confidently with textual data and excel in programming challenges.
Interview Questions
1. What is the difference between strlen()
and sizeof()
for Strings in C?
Company: TCS
Answer:strlen()
returns the length of the string excluding the null terminator, while sizeof()
gives the total memory allocated, including the null terminator.
Example:
char str[20] = "Hello"; printf("%lu %lu\n", strlen(str), sizeof(str)); // Outputs: 5 20
2.How can you detect if a string is a rotation of another string?
Company: Amazon
Answer:
To check if a string is a rotation of another, concatenate the original string with itself and check if the second string is a substring of the concatenated string.
Example Code:
#include <stdio.h> #include <string.h> int is_rotation(const char* str1, const char* str2) { if (strlen(str1) != strlen(str2)) return 0; char temp[200]; // Ensure the size is sufficient. strcpy(temp, str1); strcat(temp, str1); return strstr(temp, str2) != NULL; } int main() { char str1[] = "amazon"; char str2[] = "azonam"; if (is_rotation(str1, str2)) { printf("Strings are rotations of each other.\n"); } else { printf("Strings are not rotations of each other.\n"); } return 0; }
3.Explain the difference between strcpy()
and strncpy()
and provide a use case for strncpy()
.
Company: Apple
Answer:
strcpy()
: Copies the entire source string into the destination string, assuming enough space is available.strncpy()
: Copies up to a specified number of characters, ensuring controlled copying but doesn’t guarantee null termination if the source string exceeds the limit.
Use Case for strncpy()
: When you need to copy part of a string or ensure the destination buffer doesn’t overflow.
QUIZZES
Strings in C Quiz