0

In my Arduino project, a string will be received. I understand using .indexof to find the placement of a certain character in the string. My problem is that I need to find the first occurrence of any letter A-Z and haven't found any resources regarding using or statements in an .indexof aka string.indexof("a" || "b" ....).

Is this something that is not possible using indexof functions and if so is there any function that I can use to solve this! Thanks!

2

1 Answer 1

2

Here are two functions that I hope help in your endeavours. You can supply either a String or a char array and you should get the first position of an alpha character. Returns -1 if not present.

See https://www.arduino.cc/reference/en/language/functions/characters/isalpha/

Update:

Thanks to great comments from Edgar & Mat I have updated the functions with best practise and cost improvements.

int alphaPos(const char* str)
{
  for (int i = 0; str[i] !=0 ; ++i) {
    if (isAlpha(str[i]))
    {
      return i;
    }
  }
  
  return -1;
}


int alphaPos(const String& str)
{
  return alphaPos(str.c_str());
}

/*
    Usage:

    String bobble = "&&&88434a";
    int x = alphaPos(bobble);

    if (x != -1) 
    {
      ...x has the position in the string
    }
    else
    {
     ...There is no alpha char present.
    }
*/
6
  • I suggest passing a const reference to the second overload. Commented Jul 27, 2021 at 7:17
  • @EdgarBonet, I admit I have much to learn so ask honestly what the benefit is? Commented Jul 27, 2021 at 7:44
  • @voidPointer: it indicates to the caller that the function will not modify the passed String. It is good practice. Also you can avoid the strlen call (which doubles the cost of the function) - use str[i] != 0 in the loop condition instead.
    – Mat
    Commented Jul 27, 2021 at 8:19
  • @Mat. Thanks. That strlen tip is pretty cool and will help others too. Commented Jul 27, 2021 at 9:10
  • To elaborate on Mat's comment: if you wan to get an idea of why it is considered good practice, see Const Correctness on the isocpp.org wiki. Commented Jul 27, 2021 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.