C Programming Examples Tutorial Index

C String Programs

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

  1. Initialize Variables: Declare a character array (string) to store the input and another for the output.
  2. Input String: Prompt the user to enter a string. Use the gets() or fgets() function to take input.
  3. Remove Spaces: Iterate through each character of the string. If a character is not a space, append it to the output string.
  4. 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.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram