读取std :: string,从std :: string中删除所有特殊字符 [英] Reading std::string, remove all special characters from a std::string

查看:2625
本文介绍了读取std :: string,从std :: string中删除所有特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个论坛和c ++非常新。所以请原谅我的疑问/问题。我试图读取一个 std :: string 。我知道我可以使用 [int] 操作符访问元素。我有2个问题:

I am very new to this forum and c++. So pardon me for my doubts/ questions. I am trying to read a std::string. I know I can access the elements using at or [int] operator. I've 2 questions:

1)删除或清除字符串中的所有特殊字符(包括空格)

1) remove or erase all special characters from string (includes spaces)

2)只读这个字符串的前4个字符或字母

2) read only first 4 characters or letters from this string

对于1),我检查 std :: erase std :: remove_if 但我需要消除所有我的意思是特殊字符和空格。这意味着我需要包括 isspace() / isalpha()等所有条件。

For 1), I am checking on std::erase and std::remove_ifbut I need to eliminate all I mean special characters and spaces too. This means I need to include all the conditions that isspace()/ isalpha() and so on. Is there no single method to remove all at once?

对于2),我可以像数组一样访问字符串,我的意思是string [0],string [1] ,string [2],string [3]。

For 2), I can access the string like an array, I mean string[0], string[1], string[2], string[3]. But I can't add this into single string?

请让我知道如何实现这个?

Please let me know how can I achieve this?

推荐答案

要获得前四个字符:

std::string first4=str.substr(0, 4);

删除isspace和isalpha谓词的所有内容(虽然我认为我误解了,并不是isalpha ??):

To remove anything that isspace and isalpha predicates (although I think I misunderstood, here, do you mean isspace and is not isalpha??):

str.erase(std::remove_if(str.begin(), str.end(),
    [](char c) { return std::isspace(c) || std::isalpha(c); } ),
    str.end());

您可以使用 op + = 。例如:

str+="hello";
str+='c';

这篇关于读取std :: string,从std :: string中删除所有特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆