1

I have a incoming string like this :- *DDMMYYHHMMSS# DD Stands for Date, MM stands for month, YY stands for year, HH stands for Hour...

Example *021216213940# (Date : 2nd December, 2016 Time : 21:29:40)

How can I extract values from above given string and copy to int data type.

int Date,Month,Year,Hours,Minutes,Seconds;
10
  • int Date = (str[1] - '0') * 10 + str[2] - '0'. Commented Dec 1, 2016 at 20:59
  • Why multiply by 10? Commented Dec 1, 2016 at 21:02
  • You multiply by 10 to get the "tens". For example if the first digit is 2 then 2 * 10 = 20. Commented Dec 1, 2016 at 21:06
  • For example if incoming string is like *021216213940# (Date : 2nd December, 2016 Time : 21:29:40). How to extract the date and month? Commented Dec 1, 2016 at 21:07
  • @freestyle has it. Commented Dec 1, 2016 at 21:15

2 Answers 2

2

You can use scanf family functions, like this:

char *incoming = "*021216213940#";
int day, month, year, hours, minutes, seconds;
if (6 != sscanf(incoming, "*%2d%2d%2d%2d%2d%2d#", &day, &month, &year, &hours, &minutes, &seconds))
{
    ... /* handle invalid input here */
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1. Just like to add that sscanf can be used if the input is already located in a string. Like char* p = "*021216213940#"; if (6 != sscanf(p, "*%2d%2d%2d%2d%2d%2d#", &day, &month, &year, &hours, &minutes, &seconds)) { /* error handlind */ }
1

To convert the content of your string you need to convert to (a two digit) decimal, which is a ten-based positional system.

For example to extract the first two digits you use subscript operator[], i.e. str[1] and str[2], to convert from char to int you subtract '0' character utilising ASCII character ordering and finally to ensure correct position of the digits you multiply by 10:

int DD = (str[1] - '0') * 10 + str[2] - '0';

4 Comments

Random name of a variable, the first two digits of your string, it should be day, I guess.
Is everything else comprehensible enough? Do you need further elaboration?
Um, That's enough I guess.
Great, happy to help!

Your Answer

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.