Qbasicnews.com

QBasic => QB Discussion & Programming Help => Topic started by: techdude2007 on May 10, 2008, 07:44:48 PM



Title: Search inside Integers
Post by: techdude2007 on May 10, 2008, 07:44:48 PM
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?


Title: Re: Search inside Integers
Post by: roy on May 10, 2008, 08:19:00 PM
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



Title: Re: Search inside Integers
Post by: Ralph on May 11, 2008, 01:34:10 AM
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.


Title: Re: Search inside Integers
Post by: LPG on May 11, 2008, 01:51:04 AM
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?


Title: Re: Search inside Integers
Post by: Ralph on May 11, 2008, 03:14:41 AM
Very ingenious LPG, I would not have thought of doing it that way!  It is certainly much quicker than the other way!


Title: Re: Search inside Integers
Post by: LPG on May 12, 2008, 02:54:57 AM
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.


Title: Re: Search inside Integers
Post by: Ralph on May 12, 2008, 12:45:24 PM
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.