Remove Spaces from String in C
Removing spaces from a string is one of the most common string manipulation tasks in C programming. Whether you are cleaning user input, preparing data for processing, or building text-based applications, understanding how to efficiently remove spaces is an essential skill for every C programmer.
In C, strings are stored as arrays of characters terminated by a null character ('\0'). Unlike higher-level languages, C does not provide a built-in function specifically for removing spaces from a string. Therefore, we need to manually iterate through the string and manipulate it using loops, conditions, and sometimes pointers.
In this tutorial, you will learn multiple approaches to remove spaces from a string, including in-place modification, using an auxiliary array, and pointer-based techniques. We will also explore how each method works internally and discuss common pitfalls that beginners often encounter.
1. Basic Approach (In-Place Modification)
The most efficient way to remove spaces from a string is by modifying the string in place. This means we do not use extra memory; instead, we shift non-space characters forward in the same string.
We use two variables: one to read characters from the original string and another to write characters into the new position. Whenever we encounter a non-space character, we copy it forward. If the character is a space, we simply skip it.
#include <stdio.h>
int main() {
char str[100];
int i, j = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for(i = 0; str[i] != '\0'; i++) {
if(str[i] != ' ' && str[i] != '\n') {
str[j++] = str[i];
}
}
str[j] = '\0';
printf("String without spaces: %s", str);
return 0;
}
This method is memory-efficient because it avoids creating a second array. It is also faster in most cases since it only requires a single pass through the string.
2. Step-by-Step Explanation
Let’s understand how the algorithm works step by step. Suppose the input string is: "Hello World".
1. The loop starts from index 0 and reads each character. 2. When 'H' is found, it is copied to position j (which is also 0 initially). 3. This process continues for 'e', 'l', 'l', and 'o'. 4. When a space is encountered, it is skipped. 5. The next character 'W' is copied to the next available position. 6. This continues until the end of the string. 7. Finally, a null character is added to terminate the modified string.
At the end of execution, the string becomes "HelloWorld".
3. Using a Second Array
Another approach is to use a separate array to store the result. This method is easier to understand for beginners because it avoids modifying the original string directly.
#include <stdio.h>
int main() {
char str[100], result[100];
int i, j = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for(i = 0; str[i] != '\0'; i++) {
if(str[i] != ' ' && str[i] != '\n') {
result[j++] = str[i];
}
}
result[j] = '\0';
printf("String without spaces: %s", result);
return 0;
}
Although this approach is simpler conceptually, it uses extra memory. In real-world applications where memory efficiency matters, the in-place method is usually preferred.
4. Using Pointers
Pointers provide a more advanced and flexible way to manipulate strings in C. Instead of using array indices, we can use pointer variables to traverse and modify the string.
#include <stdio.h>
int main() {
char str[100];
char *src, *dest;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
src = dest = str;
while(*src != '\0') {
if(*src != ' ' && *src != '\n') {
*dest = *src;
dest++;
}
src++;
}
*dest = '\0';
printf("String without spaces: %s", str);
return 0;
}
This approach works similarly to the in-place method but uses pointers instead of indices. It is often preferred in low-level programming and performance-critical applications.
5. Removing All Whitespace Characters
Sometimes, you may want to remove not just spaces but all whitespace characters such as tabs (\t), newlines (\n), and carriage returns (\r).
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, j = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for(i = 0; str[i] != '\0'; i++) {
if(!isspace(str[i])) {
str[j++] = str[i];
}
}
str[j] = '\0';
printf("String without whitespace: %s", str);
return 0;
}
The isspace() function from
6. Common Mistakes
One of the most common mistakes is forgetting to add the null terminator at the end of the modified string. Without it, the string may contain garbage values when printed.
Another mistake is not handling newline characters when using fgets(). Since fgets() stores the newline character, failing to remove it can lead to unexpected output.
Beginners also sometimes confuse the logic by trying to shift characters incorrectly, which can overwrite data or produce incorrect results.
Improper pointer handling can also lead to segmentation faults or undefined behavior, especially when working with pointer-based solutions.
7. Best Practices
Always ensure that your string is properly null-terminated after modification. This is critical for correct output.
Use meaningful variable names like 'readIndex' and 'writeIndex' instead of single-letter variables for better readability.
Validate input length to avoid buffer overflow issues.
When working with whitespace, consider using standard library functions like isspace() for better reliability.
Conclusion
Removing spaces from a string in C is a fundamental string manipulation task that helps you understand how character arrays work internally. By mastering this concept, you gain better control over memory and string processing.
We explored multiple approaches including in-place modification, using a second array, and pointer-based techniques. Each method has its own advantages and use cases. While beginners may find the second array method easier, experienced programmers often prefer in-place or pointer-based approaches for efficiency.
With practice, you will be able to extend this concept to more advanced string operations such as removing specific characters, trimming spaces, or parsing structured text. Keep practicing and experimenting with variations of this problem to strengthen your C programming skills.
Codecrown