使用ICU來迭代字符串並檢查是否滿足適當的Unicode屬性。這裏是用C來檢查UTF-8命令行參數是否是有效的標識符的一個示例:
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unicode/uchar.h>
#include <unicode/utf8.h>
int main(int argc, char **argv) {
if (argc != 2) return EXIT_FAILURE;
const char *const str = argv[1];
int32_t off = 0;
// U8_NEXT has a bug causing length < 0 to not work for characters in [U+0080, U+07FF]
const size_t actual_len = strlen(str);
if (actual_len > INT32_MAX) return EXIT_FAILURE;
const int32_t len = actual_len;
if (!len) return EXIT_FAILURE;
UChar32 ch = -1;
U8_NEXT(str, off, len, ch);
if (ch < 0 || !u_isIDStart(ch)) return EXIT_FAILURE;
while (off < len) {
U8_NEXT(str, off, len, ch);
if (ch < 0 || !u_isIDPart(ch)) return EXIT_FAILURE;
}
}
注意,這裏ICU使用Java的定義,其是從那些UAX #31略有不同。在真正的應用程序中,您可能還想在之前將其規範化爲NFC。
Unicode標準包含有關編程語言中'標識符'應允許使用哪些字符的指導原則。 C++實際上被指定遵循這些guildlines,雖然在實際的實現中支持仍然很不明顯。除了標識符和特定文字之外,您不必對字符進行分類,因爲您幾乎完全指定了每個標記。 – bames53 2013-04-07 01:46:42
我在哪裏可以找到這些指導?是否有任何C++函數,用於檢查specyfic字符是否可用於編程語言中的「標識符」(根據規範)? – 2013-04-07 02:12:35
這是關於測試有效的* C++標識符字符*或有效的*字母字符*的問題嗎? – 2013-04-07 03:58:59