问题
This may be a trivial question for some, but I cannot find an appropriate answer. What I'd like is to generate a range (let's say a std::string
) that contains all possible char
s for which std::isalpha
evaluates to true
.
For example, for the default locale, the string should be "A...Za...z"
. However, if the locale is french, for example, then accented letters should also belong to the string.
PS: I got a solution from Dieter Lücking, https://stackoverflow.com/a/25125871/3093378
It seems to work on all platforms except mine (OS X 10.9.4
g++4.9
, clang++
LLVM version 5.1 (clang-503.0.40) ), where it just segfaults when trying to access table[i]
in the line
if(table[i] & ctype::alpha)
I wonder if anyone else can reproduce the error on a Mac or any other platform.
回答1:
Instead of classifying characters by generating a set of characters, being alphabetical, you might utilize the ctype-table directly:
#include <iostream>
#include <locale>
int main() {
typedef std::ctype<char> ctype;
std::locale locale;
const ctype& facet = std::use_facet<ctype>(locale);
const ctype::mask* table = facet.table();
// You might skip this and work with the table, only.
std::string result;
for(unsigned i = 0; i < facet.table_size; ++i) {
if(table[i] & ctype::alpha)
result += char(i);
}
std::cout << result << '\n';
return 0;
}
回答2:
If you need a portable solution then I can't think of any reason running isalpha()
on all possible char
values wouldn't be your best option.
If platform specific methods are acceptable then you may be able to extract the information from the locale definitions for your platform. Here's some documentation that would help you get started on POSIX platforms: http://pubs.opengroup.org/onlinepubs/009696699/basedefs/xbd_chap07.html
来源:https://stackoverflow.com/questions/25125523/generate-range-for-which-stdisalpha-evaluates-to-true