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!
1 Answer 1
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.
}
*/
-
I suggest passing a
const
reference to the second overload.Edgar Bonet– Edgar Bonet2021年07月27日 07:17:20 +00:00Commented Jul 27, 2021 at 7:17 -
@EdgarBonet, I admit I have much to learn so ask honestly what the benefit is?voidPointer– voidPointer2021年07月27日 07:44:00 +00:00Commented 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) - usestr[i] != 0
in the loop condition instead.Mat– Mat2021年07月27日 08:19:37 +00:00Commented Jul 27, 2021 at 8:19 -
@Mat. Thanks. That strlen tip is pretty cool and will help others too.voidPointer– voidPointer2021年07月27日 09:10:27 +00:00Commented 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.Edgar Bonet– Edgar Bonet2021年07月27日 12:17:05 +00:00Commented Jul 27, 2021 at 12:17
isupper(char)
: cplusplus.com/reference/cctype/isupper. you can find many chars at once using cplusplus.com/reference/cstring/strcspn