[SOLVED] How can I determine if a string is all AlphaNumeric?

Special characters in file names can make my sketch go nutsy. So I want to recognize only those files that are purely AlphaNumeric.

I think it should be a function something like this:

boolean isAlphaNumeric(String str)
{
    int len = str.length();
    for (int i=0; i<len; i++)
        if (!str[i].match("[a-zA-Z0-9.]"))
            return false;
    return true;
}

How can I best accomplish this in the Arduino language?

First of all, that is the Arduino language. But don't use the String class. Use char strings.

Use isalpha().

if (not isalpha(str[i]))
            return false;

But you have to make str a char array.

Well, a good start, but it didn't quite work out for me.

Here's what the Serial Monitor window produced to show what was happening:

SD Card started.
str:11230932.MP3
false:0
str:11241252.MP3
false:0
str:11251051.MP3
false:0
str:1124$252.MP3
false:0
str:11230#93.MP3
false:0
str:112@1051.MP3
false:0
str:GB231239.MP3
false:2
str:GB231046.MP3
false:2
audioFCnt-saved:0

I see what isalpha() is doing, is counting how many letters there are in the string, ignoring both numbers and special characters. Each file name came back zero, except for the last two, because they both have the letters "GB" in their name.

What I need is to accept numbers, the period, and letters; and reject all other characters.

You’ll need to test three ways then.

Assuming we have a char array and not a String:

bool isAlphaNumerAndPeriod(char* instr){
   
      for(int i = 0; i < strlen(instr); i++){
           if(isalpha(instr[i])){
               continue;
           }
           if(isdigit(instr[i])){
               continue;
           }
           if(instr[i] == '.'){
               continue;
           }
           return false;
      }
      return true;
}

Also see isalnum.

So this can lose one comparison then:

bool isAlphaNumerAndPeriod(char* instr){
   
      for(int i = 0; i < strlen(instr); i++){
           if(isalnum(instr[i])){
               continue;
           }
           if(instr[i] == '.'){
               continue;
           }
           return false;
      }
      return true;
}

I would do it like so

bool isFileNameValid( const char * fileName )
{
  char c;
  while ( (c = *fileName++) )
    if ( c != '.' && !isalnum(c) )
      return false;
  return true;
}

Edit: simplified my code

Thank you guys, for taking the time to give me your ideas.

It only took changing three letters -- from "isalpha" to "isalnum" to make the function work correctly. Now the printout is:

SD Card started.
str:11230932.MP3
true:8
str:11241252.MP3
true:8
str:11251051.MP3
true:8
str:1124$252.MP3
false:4
str:11230#93.MP3
false:5
str:112@1051.MP3
false:3
str:GB231239.MP3
true:8
str:GB231046.MP3
true:8
audioFCnt-saved:5

Totally perfect!