Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Search inside Integers
#1
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?
Reply
#2
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
Reply
#3
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.
Ralph, using QuickBASIC 4.5 and Windows XP Home Edition and Service Pack 2, with HP LaserJet 4L printer.
Reply
#4
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?
WHILE RPG$ <> "complete" : make up silly excuses :WEND
Reply
#5
Very ingenious LPG, I would not have thought of doing it that way!  It is certainly much quicker than the other way!
Ralph, using QuickBASIC 4.5 and Windows XP Home Edition and Service Pack 2, with HP LaserJet 4L printer.
Reply
#6
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.
WHILE RPG$ <> "complete" : make up silly excuses :WEND
Reply
#7
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.
Ralph, using QuickBASIC 4.5 and Windows XP Home Edition and Service Pack 2, with HP LaserJet 4L printer.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)