简体   繁体   中英

How to remove whitespace from a expression using a function with const char* pointer

I am working with a small piece of code and want to remove all the whitespaces from a simple expression. I am taking char array expression and passing it to an function with const char* pointer,but i am not able to remove the whitespace. here is what i tried, but didn't get desired output.

#include <iostream>

using namespace std;

void evaluate(const char *expression){

if (*expression == '\0') cout<<"Invalid"<<endl;

while(*expression){
    if(*expression == ' '){
        *expression++ ;
    }
    expression++;
 }

cout<<expression;

}

int main()
{
    char expr[] = "1 + 2 * 3";
    evaluate(expr);
    return 0;
}

It will be great if someone can help me with this. Thanks in advance.

Use std::string and the erase-remove idiom

#include <iostream>
#include <string>

void evaluate(const char *expression){
    if (*expression == '\0') std::cout << "Invalid\n";

    std::cout << expression;
}

int main()
{
    char expr[] = "1 + 2 * 3";
    std::string exprString = expr;
    exprString.erase(
        std::remove(std::begin(exprString), std::end(exprString), ' '),
        std::end(exprString));
    evaluate(exprString.c_str());
    return 0;
}

In this code I added string but I recommend to completely remove the C-strings in this code and replace them by std::string.

You can't change the C-string inside the function because it's const.

If I understand your intent is simply to output the expression without spaces when calling evaluate() , you can simplify things by outputting each character that is not a space with:

#include <iostream>

using namespace std;

void evaluate (const char *expression) {

    if (!*expression) {
        cout << "Invalid\n";
        return;
    }

    while (*expression) {
        if (*expression != ' ')
            cout << (char)*expression;
        expression++;
    }
    cout << '\n';
}

int main() {

    char expr[] = "1 + 2 * 3";

    evaluate(expr);
}

Example Use/Output

$ ./bin/rmws_const_char
1+2*3
*expression++

This only increments the pointer (and needlessly evaluates what it was pointing at). It does not modify the original character array.

If you want the expression in memory without spaces, rather than just for output purposes, I suggest that you build a new array with the spaces removed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM