简体   繁体   English

检查string.at(i)是否是空格C ++

[英]Check if string.at(i) is a whitespace C++

I want to check if a char ( string.at(i) ) is whitespace in C++. 我想检查一下charstring.at(i) )是否是C ++中的空格。 How can I do this easily? 我怎么能这么容易做到?

I got this code example, and I was thinking to change the _____ with something, but don't know what. 我得到了这个代码示例,我正在考虑用某些东西改变_____ ,但不知道是什么。 I've tried with ' ' , but that didn't work. 我试过' ' ,但那没用。

for(int i = 0; i < string.length(); i++)
{
    if(string.at(i) == _________)
    {
        //do something
    }
}
#include <cctype>

if (isspace(string.at(i)))

Instead of == [something], you want: if (isspace(string.at(i)) (or you might prefer to use std::isspace ). 而不是== [something],你想要: if (isspace(string.at(i)) (或者你可能更喜欢使用std::isspace )。

Edit: I should add that depending on what you're doing with the space characters (or what you're going with everything else, depending) you might want to use an algorithm. 编辑:我应该添加,这取决于你正在使用空格字符什么(或者你要用其他所有东西,取决于你),你可能想要使用算法。 Just for example, if you wanted to create a copy of your string with all the whitespace characters removed, you could use: 例如,如果您想创建一个删除了所有空白字符的字符串副本,您可以使用:

std::remove_copy_if(s.begin(), s.end(), std::back_inserter(new_string), isspace);

Unrepentant C programmers migrating to C++ would semi-automatically use: 迁移到C ++的不悔改的C程序员会半自动使用:

#include <cctype>

if (std::isspace(string.at(i)))
    ...

It is quite likely to be the correct even for C++ programmers. 即使对于C ++程序员来说,它也很可能是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM