wordpress clean name spaces
#include <stdio.h>
#include <string.h>
void cleanNameSpaces(char *str) {
int i, j;
int length = strlen(str);
int inside_space = 0;
for (i = 0, j = 0; i < length; i++) {
if (str[i] != ' ') {
str[j++] = str[i];
inside_space = 0;
} else {
if (!inside_space) {
str[j++] = str[i];
inside_space = 1;
}
}
}
str[j] = '\0';
}
int main() {
char str[100];
printf("Enter a string with extra spaces: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // Remove newline character
cleanNameSpaces(str);
printf("String after removing extra spaces: %s\n", str);
return 0;
}
Explanation:
#include <stdio.h>
: Includes the standard input-output header file for input/output operations.#include <string.h>
: Includes the string manipulation functions header file.void cleanNameSpaces(char *str)
: Function declaration forcleanNameSpaces
that takes a string pointerstr
as input and removes extra spaces from it.int i, j;
: Declaration of variables for looping through the string.int length = strlen(str);
: Calculates the length of the input string usingstrlen
function from<string.h>
.int inside_space = 0;
: Flag to track whether the loop is inside consecutive spaces or not.for (i = 0, j = 0; i < length; i++) { ... }
: Loop to iterate through each character of the string.if (str[i] != ' ') { ... }
: If the character is not a space, it is copied to the new stringstr[j++]
.else { ... }
: If the character is a space, it checks whether it's already inside a consecutive space or not.str[j] = '\0';
: Adds the null terminator at the end of the modified string to signify the end of the string.int main() { ... }
: Entry point of the program.char str[100];
: Declares a character array to store the input string.printf("Enter a string with extra spaces: ");
: Asks the user to input a string with extra spaces.fgets(str, sizeof(str), stdin);
: Reads the input string from the user, including spaces, and stores it instr
.str[strcspn(str, "\n")] = '\0';
: Removes the newline character from the string input by replacing it with the null terminator.cleanNameSpaces(str);
: Calls thecleanNameSpaces
function to remove extra spaces from the input string.printf("String after removing extra spaces: %s\n", str);
: Prints the modified string after removing extra spaces.