Ispunct()不删除字符串中间的逗号

ispunct() not removing commas in the middle of a string

本文关键字:中间 字符串 删除 Ispunct      更新时间:2023-10-16

我有一个字符串,它由:

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算法(以及ispunct谓词)。

N。B:

调用remove之后通常会调用容器的erase方法,该方法会擦除未指定的值并减小容器的物理大小以匹配新的逻辑大小。

#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;
}

看它运行!

好吧,您只对test[test.length()-1](字符串中的最后一个字符)这样做。这里没有逗号,只有句号