gpt4 book ai didi

c++ - ispunct() 不删除字符串中间的逗号

转载 作者:太空宇宙 更新时间:2023-11-04 15:26:12 26 4
gpt4 key购买 nike

我有一个字符串,包括:

UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity.

我有下面的代码应该去除这个字符串中的所有标点符号。测试变量是我的字符串:

 if(std::ispunct(test[test.length()-1]))
{
test.erase(test.length()-1, 1);
}

然而,当我在这个函数之后再次输出这个字符串时,我有以下内容:

UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity

出于某种原因,ispunct 函数能够去除句号但不能去除逗号。为什么它以这种方式表现?提前致谢。

最佳答案

看起来您正在寻找 remove_if algorithm (连同 ispunct predicate )。

注意:

A call to remove is typically followed by a call to a container's erase method, which erases the unspecified values and reduces the physical size of the container to match its new logical size.

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

int main()
{
std::string dmr = "UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity.";
auto last = std::remove_if(dmr.begin(), dmr.end(), ispunct);
dmr.erase(last, dmr.end());
std::cout << dmr << std::endl;
}

See it run!

关于c++ - ispunct() 不删除字符串中间的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7801686/

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