简体   繁体   English

如何使用带有 const char* 指针的函数从表达式中删除空格

[英]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.我正在使用 char 数组表达式并将其传递给具有 const char* 指针的函数,但我无法删除空格。 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使用std::string擦除删除成语

#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.在这段代码中,我添加了字符串,但我建议完全删除这段代码中的 C 字符串,并用 std::string 替换它们。

You can't change the C-string inside the function because it's const.您不能更改函数内的 C 字符串,因为它是常量。

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:如果我理解您的意图只是在调用evaluate()时输出没有空格的表达式,您可以通过输出每个不是空格的字符来简化事情:

#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.如果您希望内存中的表达式没有空格,而不仅仅是出于输出目的,我建议您构建一个删除空格的新数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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