gpt4 book ai didi

c++ - 删除空格,转换大小写,在引号除外的字符串中

转载 作者:行者123 更新时间:2023-11-28 03:19:09 24 4
gpt4 key购买 nike

我使用的是没有 Boost 的 C++03。

假设我有一个字符串,例如.. The day is "Mon day"

我想处理这个

今天是星期一

也就是说,将不在引号中的转换为大写,并删除不在引号中的空格。

字符串可能不包含引号,但如果包含,则只有 2 个。

我尝试使用 STL 算法,但我卡在了如何记住它是否在元素之间的引号中。

当然我可以用很好的旧 for 循环来做,但我想知道是否有一种奇特的 C++ 方法。

谢谢。

这是我使用for循环的结果

while (getline(is, str))
{
// remove whitespace and convert case except in quotes
temp.clear();
bool bInQuote = false;
for (string::const_iterator it = str.begin(), end_it = str.end(); it != end_it; ++it)
{
char c = *it;

if (c == '\"')
{
bInQuote = (! bInQuote);
}
else
{
if (! ::isspace(c))
{
temp.push_back(bInQuote ? c : ::toupper(c));
}
}
}
swap(str, temp);

最佳答案

您可以使用 STL 算法执行以下操作:

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

using namespace std;

struct convert {
void operator()(char& c) { c = toupper((unsigned char)c); }
};

bool isSpace(char c)
{
return std::isspace(c);
}

int main() {

string input = "The day is \"Mon Day\" You know";
cout << "original string: " << input <<endl;

unsigned int firstQuote = input.find("\"");
unsigned int secondQuote = input.find_last_of("\"");

string firstPart="";
string secondPart="";
string quotePart="";
if (firstQuote != string::npos)
{
firstPart = input.substr(0,firstQuote);
if (secondQuote != string::npos)
{
secondPart = input.substr(secondQuote+1);
quotePart = input.substr(firstQuote+1, secondQuote-firstQuote-1);
//drop those quotes
}

std::for_each(firstPart.begin(), firstPart.end(), convert());
firstPart.erase(remove_if(firstPart.begin(),
firstPart.end(), isSpace),firstPart.end());
std::for_each(secondPart.begin(), secondPart.end(), convert());
secondPart.erase(remove_if(secondPart.begin(),
secondPart.end(), isSpace),secondPart.end());
input = firstPart + quotePart + secondPart;
}
else //does not contains quote
{
std::for_each(input.begin(), input.end(), convert());
input.erase(remove_if(input.begin(),
input.end(), isSpace),input.end());
}
cout << "transformed string: " << input << endl;
return 0;
}

它给出了以下输出:

original string: The day is "Mon Day" You know
transformed string: THEDAYISMon DayYOUKNOW

用你展示的测试用例:

original string: The day is "Mon Day"
transformed string: THEDAYISMon Day

关于c++ - 删除空格,转换大小写,在引号除外的字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15973809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com