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!

asked Jul 26, 2021 at 22:00
2
  • index is only for one comparison at a time. there's a built-in isupper(char): cplusplus.com/reference/cctype/isupper. you can find many chars at once using cplusplus.com/reference/cstring/strcspn Commented Jul 26, 2021 at 22:44
  • You can also use a for loop that checks the value of i (or whatever variable) and then depending on what i is it runs indexof with different letters. Commented Jul 26, 2021 at 23:51

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.
 }
*/
answered Jul 27, 2021 at 1:21
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. 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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.