How to determine if a string is a pure ASCII string:
Method 1: Python Implementation
pythondef is_ascii(s): try: s.encode('ascii') return True except UnicodeEncodeError: return False # Or use ord() function def is_ascii_v2(s): return all(ord(c) < 128 for c in s)
Method 2: JavaScript Implementation
javascriptfunction isASCII(str) { return /^[\x00-\x7F]*$/.test(str); } // Or use codePointAt() function isASCIIV2(str) { for (let i = 0; i < str.length; i++) { if (str.codePointAt(i) > 127) { return false; } } return true; }
Method 3: Java Implementation
javapublic static boolean isASCII(String str) { return str.chars().allMatch(c -> c < 128); } // Or use regular expression public static boolean isASCIIV2(String str) { return str.matches("\\A\\p{ASCII}*\\z"); }
Method 4: C/C++ Implementation
c#include <stdbool.h> #include <string.h> bool is_ascii(const char* str) { for (size_t i = 0; str[i] != '\0'; i++) { if ((unsigned char)str[i] > 127) { return false; } } return true; }
Method 5: Go Implementation
gofunc isASCII(s string) bool { for _, r := range s { if r > 127 { return false } } return true }
Performance Optimization Suggestions:
- Early termination: Return immediately when non-ASCII character is found
- Batch checking: Use SIMD instructions to accelerate (C/C++)
- Cache results: Cache results for repeatedly checked strings
- Use regular expressions: Suitable for simple scenarios
Important Notes:
- Empty string is considered ASCII string
- Control characters (0-31) are also ASCII
- Pay attention to string encoding format
- Consider Unicode combining characters