Check if string.at(i) is a whitespace C++
I want to check if a char
(string.at(i)
) is whitespace in C++. How can I do this easily?
I got this code example, and I was thinking to change the _____
with something,开发者_Go百科 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
).
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:
#include <cctype>
if (std::isspace(string.at(i)))
...
It is quite likely to be the correct even for C++ programmers.
精彩评论