Write a C program to remove white spaces from a string using a for loop. In this C example, for loop iterate string from the first character to the last, and the if statement checks for the empty or whitespace character. If True, the compiler will skip that character from storing it in the array.
#include <stdio.h> int main() { char str[100]; int i, j = 0; printf("Enter String to Remove White Spaces = "); gets(str); printf("String before Removing Empty Spaces = %s\n", str); for(i = 0; str[i] != '\0'; i++) { str[i] = str[i + j]; if(str[i] == ' ' || str[i] == '\t') { j++; i--; } } printf("String after Removing Empty Spaces = %s\n", str); }
It is another way of writing a c program for removing the whitespaces from a string. Here, we used the nested for loops.
#include <stdio.h> #include<string.h> int main() { char str[100]; int i, j = 0; printf("Enter String = "); gets(str); int len = strlen(str); printf("Before = %s\n", str); for(i = 0; i < len; i++) { if(str[i] == ' ' || str[i] == '\t') { for(j = i; j < len; j++) { str[j] = str[j + 1]; } len--; } } printf("After = %s\n", str); return 0; }
Enter String = c programs
Before = c programs
After = cprograms
Enter String = learn c
Before = learn c
After = learnc
C program to remove all the white spaces or blank spaces from a string using a while loop.
#include <stdio.h> int main() { char str[100]; int i, j, k; printf("Enter String = "); gets(str); printf("Before Removing = %s\n", str); i = 0; while(str[i] != '\0') { k = 0; if(str[i] == ' ' || str[i] == '\t') { j = i; while(str[j - 1] != '\0') { str[j] = str[j + 1]; j++; } k = 1; } if(k == 0) { i++; } } printf("After Removing = %s\n", str); }
Enter String = c programming exmaples
Before Removing = c programming exmaples
After Removing = cprogrammingexmaples