0

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!

MichaelT
8873 gold badges8 silver badges22 bronze badges
asked Nov 11, 2018 at 22:26
2
  • note: concatenate means join.... it is opposite of what you are trying to do, which is split Commented Nov 11, 2018 at 23:23
  • see stackoverflow.com/questions/40538792/…? Commented Nov 11, 2018 at 23:27

1 Answer 1

1

There's multiple ways.

The String class (which TBH you should avoid) has some useful methods:

  • substring - extract part of a string as a new string
  • toInt - convert a string to an integer

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.

answered Nov 11, 2018 at 22:45
3
  • 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? Commented Nov 12, 2018 at 9:50
  • Start by reading the serial properly. Start here: majenko.co.uk/blog/reading-serial-arduino Commented Nov 12, 2018 at 9:51
  • Thank you! Your link was really useful and my circuit works as intended to :) Commented Nov 12, 2018 at 11:41

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.