C program to remove white spaces from a string; Through this tutorial, we will learn how to remove white spaces from a string using for loop, recursion and while loop in c programs.
Programs to Remove White Spaces from a String in C
- C Program to Remove White Spaces from a String using For Loop
- C Program to Remove White Spaces from a String using While Loop
- C Program to Remove White Spaces from a String using Recursion
C Program to Remove White Spaces from a String using For Loop
#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); }
The output of the above c program; as follows:
Enter String to Remove White Spaces = hello world String before Removing Empty Spaces = hello world String after Removing Empty Spaces = helloworld
C Program to Remove White Spaces from a String using While Loop
#include <stdio.h> int main() { char str[100]; int i, j, k; printf("Enter String to Remove White Spaces = "); gets(str); printf("String before Removing Empty Spaces = %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("String after Removing Empty Spaces = %s\n", str); }
The output of the above c program; as follows:
Enter String to Remove White Spaces = c program String before Removing Empty Spaces = c program String after Removing Empty Spaces = cprogram
C Program to Remove White Spaces from a String using Recursion
#include <stdio.h> #include <string.h> void deleteblankspaces(char *s) { static int i,k=0; if(s[i]) { s[i]=s[i+k]; if(s[i]==' '|| s[i]=='\t') { k++; i--; } i++; deleteblankspaces(s); } } int main() { char s[1000]; printf("Enter the string : "); gets(s); deleteblankspaces(s); printf("string after removing all duplicates:"); printf("%s",s); return 0; }
The output of the above c program; as follows:
Enter the string : hello world string after removing all duplicates:helloworld