c++ - 从字符串中删除空格,不包括 "and ' C++ 对之间的部分

标签 c++ string c++11 whitespace string-parsing

所以基本上我想要做的是从 std::string 对象中删除所有空格,但是排除语音标记和引号中的部分(因此基本上是字符串),例如:

Hello, World! I am a string

会导致:

Hello,World!Iamastring

但是语音标记/引号内的内容将被忽略:

"Hello, World!" I am a string

会导致:

"Hello, World!"Iamastring

或者:

Hello,' World! I' am a string

会是:

Hello,' World! I'amastring

是否有一个简单的例程来对字符串执行此操作,或者是内置到标准库中的例程,或者是如何编写我自己的例程?它不一定是最高效的,因为每次程序运行时它只会运行一次或两次。

最佳答案

没有,没有现成的例程。

不过您可以构建自己的。

你必须遍历字符串并且你想使用一个标志。如果标志为真,则删除空格,如果为假,则忽略它们。当您不在引号中时,该标志为真,否则为假。

这是一个天真的,没有广泛测试的例子:

#include <string>
#include <iostream>
using namespace std;

int main() {
    // we will copy the result in new string for simplicity
    // of course you can do it inplace. This takes into account only
    // double quotes. Easy to extent do single ones though!
    string str("\"Hello, World!\" I am a string");
    string new_str = "";
    // flags for when to delete spaces or not
    // 'start' helps you find if you are in an area of double quotes
    // If you are, then don't delete the spaces, otherwise, do delete
    bool delete_spaces = true, start = false;
    for(unsigned int i = 0; i < str.size(); ++i) {
        if(str[i] == '\"') {
            start ? start = false : start = true;
            if(start) {
                delete_spaces = false;
            }
        }
        if(!start) {
            delete_spaces = true;
        }
        if(delete_spaces) {
            if(str[i] != ' ') {
                new_str += str[i];
            }
        } else {
            new_str += str[i];
        }

    }
    cout << "new_str=|" << new_str << "|\n";
    return 0;
}

输出:

new_str=|"Hello, World!"Iamastring|

关于c++ - 从字符串中删除空格,不包括 "and ' C++ 对之间的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33453001/

相关文章:

c++ - 如何在 std::vector<T> 和 std::vector<std::reference_wrapper<T>> 之间进行比较和赋值?

c++ - 无需动态转换即可复制派生类属性的方法

python-3.x - 将 Pandas 数据框中的 ID 列拆分为多列

java - 用于十六进制到二进制转换的填充,以便每个十六进制数字产生 4 位

C++11 纯右值 id 表达式?

c++ - 一种按索引过滤范围,仅从过滤后的索引中获取 min_element 的方法?

c++ - c++中结构和类中的析构函数

c++ - 内存映射和排序文件后字节下落不明

映射中的 C++ 结构作为值 - 错误 "no instance of overloaded function matches the argument list"

java - 自守数 - Java 程序