所以基本上我想要做的是从 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/