Identifying characters in strings
What is the shortest way to check if a string contains the character "-" or it con开发者_如何转开发tains only numbers?
Edit: And how would I do it in C without std::string? Which one is better?
std::string
has a member function, find
, which can be used to search for a character or substring. It returns std::string::npos
if the search character or substring is not found.
One straightforward way to test whether a string contains only digits is to use the find_first_not_of
member function with the search list "0123456789"
. If it returns std::string::npos
, the string contains only digits; if it returns any other value, there is some other, nondigit character in the string.
To check if it contains any character for eg. "-"
you can use the strchr()
c library call.
As to checking if a string contains only numbers you most probably have to iterate through all characters and check if it is a digit using isdigit()
c library call.
As for the C++ way take a look at James McNellis's answer.
std::string myStr = "999-111-100";
if(myStr.find("-")!=std::string::npos)
{
//string has a - in it
}
精彩评论