乐闻世界logo
搜索文章和话题

How to determine if a string is a pure ASCII string

2026年2月21日 16:18

How to determine if a string is a pure ASCII string:

Method 1: Python Implementation

python
def 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

javascript
function 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

java
public 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

go
func isASCII(s string) bool { for _, r := range s { if r > 127 { return false } } return true }

Performance Optimization Suggestions:

  1. Early termination: Return immediately when non-ASCII character is found
  2. Batch checking: Use SIMD instructions to accelerate (C/C++)
  3. Cache results: Cache results for repeatedly checked strings
  4. 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
标签:ASCII