In C programming, removing unnecessary spaces from a string is common, mostly when dealing with user input or data processing. This tutorial will guide you in creating a C program to remove spaces from a string, providing explanations and a code example.
What is String Space Removal?
String space removal involves iterating through a string and eliminating all its spaces. For instance, if you have a string "Hello World ", the goal is to transform it into "HelloWorld". This process is commonly used in programming for data formatting and cleaning purposes.
Algorithm to Remove Spaces from a String
- Initialize Variables: Declare a character array (string) to store the input and another for the output.
- Input String: Prompt the user to enter a string. Use the
gets()
orfgets()
function to take input. - Remove Spaces: Iterate through each character of the string. If a character is not a space, append it to the output string.
- Output Result: Display the string after removing spaces.
Code Example
Here's a C program that removes spaces from a given string:
#include <stdio.h>
int main() {
char input[100], output[100];
int i, j = 0;
// Take user input for the string
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
// Iterate through the string and remove spaces
for(i = 0; input[i] != '\0'; ++i) {
if(input[i] != ' ') {
output[j++] = input[i];
}
}
output[j] = '\0'; // Null-terminate the output string
// Display the result
printf("String after removing spaces: %s\n", output);
return 0;
}
Program Output:
For example, if you input the "Hello World "string, the program processes and displays the string as "HelloWorld".
Enter a string: Hello World
String after removing spaces: HelloWorld
Conclusion
Writing a C program to remove spaces from a string is a straightforward but necessary task. It helps you understand the basics of string manipulation in C. This is beneficial for formatting and clearing program data input, a common requirement in various programming applications. By following this tutorial, you can confidently implement space removal in your C programming tasks.