Lets say I have
String myString="AR0236";
I wish to extract the number 236 and assign it to an int
. How can this be done?
P.S: I'me new to programming and I tried searching the forums for similar problems but surprising none of them worked for me!
1 Answer 1
There's multiple ways.
The String class (which TBH you should avoid) has some useful methods:
So you can join them together:
int val = myString.substring(3).toInt();
That's the easy way. Grab the string content from the 4th character (it's zero-based, so 3 is the 4th character) onwards, and convert it to an integer.
If you are avoiding String, as you should, then you are working with pointers. For instance:
char myString[10]; // This is where your data gets stored
strcpy(myString, "AR0236"); // Let's put in some dummy data
int val = atoi(myString + 3);
myString + 3
gives you a new string pointer to a location that is 3 bytes further up in memory from myString
- which equates to where the start of your number is. Then convert that portion of the string to an integer.
The "easy" way consumes and makes a mess of your heap, since it's having to make a new String object and copy data into it. The "better" (second) way uses no more memory. It just converts a subset of the existing string directly.
-
Thank you for your response. The first method works although with a bit of a delay. I wish to use the second and more efficient method but doesnt work if i pass a variable in the second argument of the strcpy. The string I want to convert is from the serial so I the the string is unknown. How would you get around this?Razib Sarker– Razib Sarker2018年11月12日 09:50:15 +00:00Commented Nov 12, 2018 at 9:50
-
Start by reading the serial properly. Start here: majenko.co.uk/blog/reading-serial-arduinoMajenko– Majenko2018年11月12日 09:51:37 +00:00Commented Nov 12, 2018 at 9:51
-
Thank you! Your link was really useful and my circuit works as intended to :)Razib Sarker– Razib Sarker2018年11月12日 11:41:49 +00:00Commented Nov 12, 2018 at 11:41
join
.... it is opposite of what you are trying to do, which issplit