You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何移除字符串中的数字并保留下划线?

解决方法:保留下划线输出Hello_World

你的代码现在会把所有非字母字符(包括下划线、数字和空格)都过滤掉,所以最后得到的是纯字母的HelloWorld。要保留下划线,只需要调整remove_if里的判断逻辑就行。

修改后的完整代码

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

int main() {
    std::string s = "Hello_World 1 2"; 
    s.erase(std::remove_if(s.begin(), s.end(), [](char c) { 
        // 只移除既不是字母也不是下划线的字符
        return !std::isalpha(c) && c != '_'; 
    } ), s.end());
    // 此时s的值就是"Hello_World"
    return 0;
}

逻辑说明

原来的判断条件!isalpha(c)会把所有不是字母的字符都标记为需要删除,包括下划线。现在我们把条件改成只有当字符既不是字母,也不是下划线的时候才删除,这样下划线就会被保留下来,而数字和空格这些不需要的字符依然会被过滤掉,正好符合你的需求。

另外提醒一下:记得包含<cctype>头文件来使用std::isalpha,同时尽量使用std::前缀避免命名空间冲突哦。

内容的提问来源于stack exchange,提问作者Tommys Gian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:32:11