Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove extra white spaces in C++

I tried to write a script that removes extra white spaces but I didn't manage to finish it.

Basically I want to transform abc sssd g g sdg gg gf into abc sssd g g sdg gg gf.

In languages like PHP or C#, it would be very easy, but not in C++, I see. This is my code:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <unistd.h>
#include <string.h>

char* trim3(char* s) {
    int l = strlen(s);

    while(isspace(s[l - 1])) --l;
    while(* s && isspace(* s)) ++s, --l;

    return strndup(s, l);
}

char *str_replace(char * t1, char * t2, char * t6)
{
    char*t4;
    char*t5=(char *)malloc(10);
    memset(t5, 0, 10);
    while(strstr(t6,t1))
    {
        t4=strstr(t6,t1);
        strncpy(t5+strlen(t5),t6,t4-t6);
        strcat(t5,t2);
        t4+=strlen(t1);
        t6=t4;
    }

    return strcat(t5,t4);
}

void remove_extra_whitespaces(char* input,char* output)
{
    char* inputPtr = input; // init inputPtr always at the last moment.
    int spacecount = 0;
    while(*inputPtr != '\0')
    {
        char* substr;
        strncpy(substr, inputPtr+0, 1);

        if(substr == " ")
        {
            spacecount++;
        }
        else
        {
            spacecount = 0;
        }

        printf("[%p] -> %d\n",*substr,spacecount);

        // Assume the string last with \0
        // some code
        inputPtr++; // After "some code" (instead of what you wrote).
    }   
}

int main(int argc, char **argv)
{
    printf("testing 2 ..\n");

    char input[0x255] = "asfa sas    f f dgdgd  dg   ggg";
    char output[0x255] = "NO_OUTPUT_YET";
    remove_extra_whitespaces(input,output);

    return 1;
}

It doesn't work. I tried several methods. What I am trying to do is to iterate the string letter by letter and dump it in another string as long as there is only one space in a row; if there are two spaces, don't write the second character to the new string.

How can I solve this?

like image 768
Damian Avatar asked Feb 09 '16 20:02

Damian


People also ask

How do I get rid of extra white spaces in a string?

If you are just dealing with excess whitespace on the beginning or end of the string you can use trim() , ltrim() or rtrim() to remove it. If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " " .

How can I remove the leading spaces from a string in C?

Below are the steps: Initialize count = 0 to count the number of leading spaces. Iterate through given string and find the index(say idx) at which the leading space character ends. Iterate through all the characters from that index idx and copy each character from this index to the end to the front index.

How do I remove extra spaces between words in C #?

Trim() Removes all current string's leading and trailing white-space characters. Trim(Char) Removes all leading and trailing instances of a character from the current string. Trim(Char[]) Removes all leading and trailing occurrences of a set of characters specified in an array from the current string.


2 Answers

There are already plenty of nice solutions. I propose you an alternative based on a dedicated <algorithm> meant to avoid consecutive duplicates: unique_copy():

void remove_extra_whitespaces(const string &input, string &output)
{
    output.clear();  // unless you want to add at the end of existing sring...
    unique_copy (input.begin(), input.end(), back_insert_iterator<string>(output),
                                     [](char a,char b){ return isspace(a) && isspace(b);});  
    cout << output<<endl; 
}

Here is a live demo. Note that I changed from c style strings to the safer and more powerful C++ strings.

Edit: if keeping c-style strings is required in your code, you could use almost the same code but with pointers instead of iterators. That's the magic of C++. Here is another live demo.

like image 88
Christophe Avatar answered Oct 02 '22 10:10

Christophe


Here's a simple, non-C++11 solution, using the same remove_extra_whitespace() signature as in the question:

#include <cstdio>

void remove_extra_whitespaces(char* input, char* output)
{
    int inputIndex = 0;
    int outputIndex = 0;
    while(input[inputIndex] != '\0')
    {
        output[outputIndex] = input[inputIndex];

        if(input[inputIndex] == ' ')
        {
            while(input[inputIndex + 1] == ' ')
            {
                // skip over any extra spaces
                inputIndex++;
            }
        }

        outputIndex++;
        inputIndex++;
    }

    // null-terminate output
    output[outputIndex] = '\0';
}

int main(int argc, char **argv)
{
    char input[0x255] = "asfa sas    f f dgdgd  dg   ggg";
    char output[0x255] = "NO_OUTPUT_YET";
    remove_extra_whitespaces(input,output);

    printf("input: %s\noutput: %s\n", input, output);

    return 1;
}

Output:

input: asfa sas    f f dgdgd  dg   ggg
output: asfa sas f f dgdgd dg ggg
like image 45
villapx Avatar answered Oct 02 '22 10:10

villapx