Jump to content
  • Advertisement
Sign in to follow this  
Pulse_19

Separating a number from a string

This topic is 4973 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a string in my program that is like this "jornada1" or "jornada2" and so on until the user say to stop. My question is if i can separate the numeric part from the rest so i can get the number 1,2,....,23. I'm using C and yes it is a school project but just a small part of it the rest i can handle :P, and yes i've search on the internet (not very much just a little).

Share this post


Link to post
Share on other sites
Advertisement
If you look in ctype.h, you'll find the function isalpha(). Just make a loop to look through the string, character by character, till you find an alphanumerical character (or you hit the end of the string). Then use atoi() (in stdlib.h) to convert that number from a string to an integer.

Share this post


Link to post
Share on other sites
What you want to do, is go and search the string.

Start at the start

Chat* Start

You then keep going until you find something thats between '0' and '9'.

When you do, you add that to the other string (just malloc an array the same size as your origional string. it may waste space, buts its easy to do).

Now, what you should do, is in between numbers, put a space character between them.

So, you need to keep a little bit of state. just a bool to say wether or not we nee dto shove in the space chr.

Whenever you set a number, you set it to true. when your not on a number, and the space bool is true, you set it to false, and you go and add the space to the character.

So, once you've done all that, you add a \0 to the end of the other string, and free the rest of the string.

you end up with something which turns
"Hefawef12324weafnewwa45#Q$#EDAdar*QY#%(#eda352"
into
"12324 45 352"

Thats what you asked for, wasn't it?
I'm not going to give code.

From,
Nice coder

Share this post


Link to post
Share on other sites
Following up on the <ctype> hint, there is also defined 'isdigit' which you should use instead of manually looking for the character range '0' to '9'.

If you want to extract the actual number, you'll need to use atoi() (from stdlib.h), passing it the position in the input where the first digit is. (Depending on your situation you may need the more general strtol() instead.)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!