Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a character is in a given range of characters?

Tags:

c++

ascii

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.

like image 841
kingboonz Avatar asked Apr 08 '14 14:04

kingboonz


People also ask

How do you know if a char is between Z?

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.

How do you check if a character is between A and Z Python?

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)!

How do you check if letters are in a string?

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.


2 Answers

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.

like image 155
Dex Avatar answered Oct 15 '22 13:10

Dex


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.

like image 42
Shoe Avatar answered Oct 15 '22 13:10

Shoe