I can seem to figure out how to seperate a letter identifier from a number in a string. For example trying to seperate Q10 into two parts Q and 10. Any help is greatly appericated Thanks!
-
1What do you mean by “separate”? Is the letter always the first character in the string and the rest is the number? What do you want to do with the number, just print it out, or actually do math to it? – Daniel H Nov 29 '18 at 20:17
-
2Have you tried something? Post it. – NiVeR Nov 29 '18 at 20:17
-
only a single letter and 2 digits or any number of letters and digits or? – kenny Nov 29 '18 at 20:17
-
So I am trying to comapre one identifer with another. I.e Q10 with E2, it will always be in the order, Letter then number with a max of two digits in the number. – Nathan Barry Nov 29 '18 at 20:22
-
assuming the you have a char* to hte start of the string sptr, look at atoi(++sptr) https://www.tutorialspoint.com/c_standard_library/c_function_atoi.htm – kenny Nov 29 '18 at 20:30
2 Answers
You can use the function isdigit
in <ctype.h>
to determine when to stop incrementing a pointer to the string:
char *p = str;
while(*p)
{
if(isdigit(*p)) break;
p++;
}
puts(p);
If there is no number in str
, the puts
line will output a newline and nothing else.

- 20,656
- 7
- 53
- 85
There are suggestions to use some functions from other libraries but you can do it yourself.
First of all you need to iterate over a whole string char by char. To do that check this question.
Now we know how to do this we need to know what to do with given char and see is it number or letter or something else.
Each char
has it's representing value from ascii
table.
If for example we have char a = '1'
in ascii
code it is represented as 49
.
So now we can do something like this:
char test = '5';
if(test >= 48 && test <= 57) //These represents numbers in ascii
{
// Do something since our char is number
}
else if(test >= 65 && test <= 90) // These represents Higher Up Letters
{
// Do something with higher up letter
}
else if(test >= 97 && test <= 122) // These represents lower case letters
{
// Do something
}
else
{
// It is not number, nor lower case letter, nor higher case letter
}
Now if we implement this in our loop you can do whatever you want, maybe store all number in one string and characters in other, or add them up or something else, it is up to you.

- 2,394
- 3
- 23
- 54
-
2This assumes that the character set is ASCII. This is not always the case. The truly portable way to test for a digit in a string is to use `isdigit`. – Govind Parmar Nov 29 '18 at 20:27
-
@GovindParmar You are right and i will mention that but since this is basic question i assume he is beginner and wanted to make him understand it more in deep than just using some built in function. – Aleksa Ristic Nov 29 '18 at 20:56