Qbasicnews.com

Full Version: Search inside Integers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I need to find a function or command that will search inside an Integer.  I am trying to see how many times the number 5 would appear in, for example, 448567475.  The user enters in a number, and the computer will find how many times the number 5 is in that integer.

I tried to use the INSTR command, but it only indicates where the 1st occurance is, not the 2nd or third.

Any ideas?
This may not be the shortest way but it works.
Code:
DIM a AS LONG
CLS

REM Your input routine goes here.
a = 233454535

b$ = STR$(a)
FOR i = 1 TO LEN(b$)
IF VAL(MID$(b$, i, 1)) = 5 THEN tot = tot + 1
NEXT
PRINT "Number of fives = "; tot
SYSTEM
Roy, I think that your solution has the correct approach.  I don't think there is another way that would be more practical and logical.
could you do it like this?

Code:
CLS

INPUT A$
S$ = "5"

1 IF INSTR(A$,S$) <> 0 THEN : TOT = TOT + 1 : A$ = RIGHT$(A$,LEN(A$)-INSTR(A$,S$)) : GOTO 1

PRINT "THERE ARE ";TOT;" `"; S$ ; "`'S"
SYSTEM

This works differently

What do you want it for?
Very ingenious LPG, I would not have thought of doing it that way!  It is certainly much quicker than the other way!
If it is inputting a sring I probably should have done this:

Code:
CLS ' 5 finder.v2

NUMBER$ = "1234567890"
IN:
INPUT "PLEASE ENTER A NUMBER";A$
FOR B = 1 TO LEN(A$)
NUM = 0
FOR C = 1 TO 10
  IF MID$(A$,B,1) = MID$(NUMBER$,C,1) THEN NUM = 1
NEXT
IF NUM <> 1 THEN PRINT "YOU DIDN'T TYPE A NUMBER." : GOTO IN
NEXT


S$ = "5"

1 IF INSTR(A$,S$) <> 0 THEN : TOT = TOT + 1 : A$ = RIGHT$(A$,LEN(A$)-INSTR(A$,S$)) : GOTO 1

PRINT "THERE ARE ";TOT;" ";CHR$(34); S$ ; CHR$(34);"'S"
SYSTEM

this checks the user inputs a number. the previous version would count the "5"'s in a phrase.
LPG:
I think that your original code is O.K., as it counts any "5" in the inputted string, whether the user enters a number or a string.  That was the OP's proposal.  Who care if one inputs a string or a number, the question is, "How many characters "5" are there in what I inputted?".  Your code answers the question correctly.