C Program Remove Blank Spaces from a given string entered by the user at run time.

Code
/* C Program to removing blank spaces from string easyCodeBook.com */ #include <stdio.h> int main() { char str1[100], str2[100]; int i, j, size = 100; printf("Enter a string to remove spaces:\n"); gets(str1); j=0; for(i=0; str1[i] != '\0'; i++) if(str1[i] != ' ') { str2[j] = str1[i]; j++; } str2[j]='\0'; printf("String with out blank spaces is: \n"); puts(str2); return 0; }
Output:
Enter a string to remove spaces: Hello World String with out blank spaces is: HelloWorld
Explanation of Logic
The given C program removes blank spaces from a string. It reads a string from the user, iterates through each character, and copies non-space characters to a new string. Finally, it prints the modified string without blank spaces.
gets(str1);
- The program starts with a multi-line comment providing a description of the program.
- The code includes the standard input/output library
stdio.h. - The
mainfunction is defined as the entry point of the program. - Inside the
mainfunction, several variables are declared:char str1[100]andchar str2[100]are arrays of characters.str1is the original string, andstr2will store the modified string without blank spaces.int iandint jare integer variables used as indices for iterating through the characters of the strings.int sizeis an integer variable initialized to 100, which represents the maximum size of the strings.
- The
printffunction is used to display a prompt message asking the user to enter a string to remove spaces. - The
getsfunction is used to read a line of input from the user and store it in thestr1array.
- The code enters a
forloop that iterates through each character of thestr1string until the null character'\0'is encountered, indicating the end of the string. - Inside the loop, an
ifcondition checks if the current characterstr1[i]is not a space' '. If the condition is true, the character is copied to thestr2string at indexj, andjis incremented. - After each iteration, the indices
iandjare incremented to move to the next character in thestr1string and the next available position in thestr2string, respectively.
- After the loop finishes, the null character
'\0'is explicitly added to thestr2string at indexjto mark the end of the string. - The
printffunction is used to display a message indicating that the string without blank spaces is about to be printed. - The
putsfunction is used to print the modified stringstr2, which contains the original string without any blank spaces. - The
return 0;statement indicates the end of themainfunction, and it signifies that the program execution was successful.
![]()