The Program in C to input any string and delete the extra blanks spaces present in the same is given below:
#include <stdio.h>
#include <stdlib.h>
void removeExtraSpaces(char *str) {
int i, j;
int count = 0;
for (i = 0; str[i]; i++) {
if (str[i] != ' ') {
str[count++] = str[i];
} else if (str[i - 1] != ' ') {
str[count++] = str[i];
}
}
str[count] = '\0';
}
int main() {
char str[100];
printf("Enter a string: \n");
gets(str);
removeExtraSpaces(str);
printf("String with extra spaces removed: %s\n", str);
return 0;
}
Output:
Enter a string:
This is a test string
String with extra spaces removed: This is a test string
Pro-Tips💡
This program uses a for loop to iterate through the characters of the input string.
If a character is not a space, it is added to the string that will be returned.
If it is a space and the previous character is not a space, it is added to the string that will be returned.
Note: gets() is a dangerous function, it doesn’t check the size of the buffer which leads to buffer overflow, it is not recommended to use it, instead you should use fgets() or scanf() to read a string from the user.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.