How to reduce spaces between two words to one space only in C

3 Answers

0 votes
#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[] = "    This   is    a    string with  multiple    spaces";
    char tmp[128] = "";
    short i = 0, j = 0;
    int size = strlen(str);
    
    // Skip leading spaces
    while (i < size && str[i] == ' ') {
        i++;
    }
    
    // Reduce spaces into a temporary string
    for (; i < size; i++) {
        if (str[i] == ' ' && tmp[j - 1] == ' ') continue;
        tmp[j++] = str[i];
    }    
    tmp[j] = '\0';

    // Copy tmp to str
    for (i = 0; i < strlen(tmp); i++) {
        str[i] = tmp[i];
    }
    str[i] = '\0';
    
    printf("\"%s\"", str);

    return 0;
}



/*
run:

"This is a string with multiple spaces"

*/


answered Jul 13, 2014 by avibootz
edited Apr 4, 2025 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void removeExtraSpaces(char* str, char* output) {
    int i = 0, j = 0;
    int n = strlen(str);
    int spaceFound = 0;

    // Skip leading spaces
    while (i < n && str[i] == ' ') {
        i++;
    }

    while (i < n) {
        if (!isspace(str[i])) {
            output[j++] = str[i];
            spaceFound = 0; // Reset the space flag
        } else if (!spaceFound) {
            output[j++] = ' '; // Add a single space
            spaceFound = 1; // Mark space as found
        }
        i++;
    }

    // Remove trailing space if any
    if (j > 0 && output[j - 1] == ' ') {
        j--;
    }

    output[j] = '\0'; // Null-terminate the output string
}

int main() {
    char str[] = "    This   is    a    string with  multiple    spaces  ";
    char output[128]; // Adjust size based on expected input length

    removeExtraSpaces(str, output);

    printf("\"%s\"\n", output);

    return 0;
}


/*
run:

"This is a string with multiple spaces"

*/

 



answered Apr 4, 2025 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

// Function to remove leading spaces and reduce multiple spaces
void removeExtraSpaces(const char* str, char* output) {
    char tmp[128] = ""; // Temporary array for processing
    short i = 0, j = 0;
    int size = strlen(str);

    // Skip leading spaces
    while (i < size && str[i] == ' ') {
        i++;
    }

    // Reduce spaces into temporary string
    for (; i < size; i++) {
        if (str[i] == ' ' && tmp[j - 1] == ' ') continue;
        tmp[j++] = str[i];
    }    
    tmp[j] = '\0';

    // Copy tmp to output
    for (i = 0; i < strlen(tmp); i++) {
        output[i] = tmp[i];
    }
    output[i] = '\0';
}

int main(void) {
    char str[] = "    This   is    a    string with  multiple    spaces";
    char result[128]; // Adjust size based on expected str length

    removeExtraSpaces(str, result);

    printf("\"%s\"", result);

    return 0;
}

 
/*
run:
 
"This is a string with multiple spaces"
 
*/

 



answered Apr 4, 2025 by avibootz
...