Check if a string is alphanumeric

Question from a community member in Discord:

I want to loop through a string and check the character is alphanumeric. 
Like in rust -- >.                
For c in input.chars(){
  if c.is_ascii_alphanumeric(){...}            
...}    

How I can achieve this in move?
2 Likes
#[test_only]
module move_tests::simple_tests {

    use std::ascii;
    use std::vector;

    const ASCII_0: u8 = 48;
    const ASCII_9: u8 = 57;
    const ASCII_A: u8 = 65;
    const ASCII_Z: u8 = 90;
    const ASCII_UPPER: u8 = 0xFF ^ 32;

    #[test]
    fun alphanumeric_test_1() {
        assert!(is_string_alphanumeric(&ascii::string(b"123abc")), 1);
        assert!(is_string_alphanumeric(&ascii::string(b"123")), 2);
        assert!(is_string_alphanumeric(&ascii::string(b"abc")), 3);
        assert!(is_string_alphanumeric(&ascii::string(b"$%#")) == false, 4);
        assert!(is_string_alphanumeric(&ascii::string(b"abc123#%^")) == false, 5);
    }

    fun is_char_alphanumeric(char: u8): bool {
        if (ASCII_0 <= char && char <= ASCII_9) {
            return true
        };

        let char = char & ASCII_UPPER;
        ASCII_A <= char && char <= ASCII_Z
    }

    fun is_string_alphanumeric(s: &ascii::String): bool {
        let b = ascii::as_bytes(s);
        let i = 0;

        while (i < vector::length(b)) {
            if (!is_char_alphanumeric(*vector::borrow(b, i))) {
                return false
            };
            i = i + 1;
        };

        true
    }

}
2 Likes