C++: How do i check if a character is between a given range of characters?
Say, if I have a string name. I want to check if the first character of this string is between 'a' to 'n'.
How do I do it?
To do (name[0] == 'a') (name[0] == 'b')... would be too long...
If possible, I would like a solution that deals with ASCII values elegantly.
if((ch >= 97 && ch <= 122) || (ch >= 65 && ch <= 90)) printf("The entered character %c is an Alphabet",ch); else printf("The entered character %c is not an Alphabet",ch); The ASCII value of 'a' is 97, 'z' is 122, 'A' is 65 and 'Z' is 90.
Python String isalpha() Method The isalpha() method returns True if all the characters are alphabet letters (a-z). Example of characters that are not alphabet letters: (space)!
You can use string. indexOf('a') . If the char a is present in string : it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
If you want to check whether or not the first character of you string is between 'a' and 'n', for instance, checking name[0] >= 'a' && name[0] <= 'n'
should do the job properly.
Keep in mind, however, that if you can also have caps as a first character in your letter, you have to check (name[0] >= 'a' && name[0] <= 'n') || (name[0] >= 'A' && name[0] <= 'N')
instead.
You can use std::all_of
in combination with a lambda expression:
std::all_of(name.begin(), name.end(), [](char i) { return (i >= 'a' && i <= 'z'); });
Live demo
This is portable enough for most application, since the character set is usually implemented following the ASCII conventions as explain in §2.3/14:
The glyphs for the members of the basic source character set are intended to identify characters from the subset of ISO/IEC 10646 which corresponds to the ASCII character set. However, because the mapping from source file characters to the source character set (described in translation phase 1) is specified as implementation-defined, an implementation is required to document how the basic source characters are represented in source files.
The complexity of the above algorithm is O(n)
. The alternative (check every character to be one in the character range with k
characters) is O(n*k)
, but at least you can be sure it's not implementation defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With