' REPEAT.BAS
' This program prompts the user for a set number of lines and a search
'   string and then prints the lines and the number of matches found.

' set maximum number of lines that can be entered and declare string
'   array to hold lines

CONST MAXLINES% = 10
DIM inputLines$(MAXLINES%)

' declare GetText subprogram and Repeat% function

DECLARE SUB GetText (inputLines$(), numOfLines%)
DECLARE FUNCTION Repeat% (search$, base$)

CLS

' call GetText subprogram to get input from user; at return the
'   numOfLines% variable will contain number of lines received

GetText inputLines$(), numOfLines%

' get pattern to be searched for from user

PRINT
INPUT "Enter the string to be searched for:  ", pattern$
PRINT

' call Repeat% function to determine the number of matches per line;
'   totalRepeats% variable tracks number of total matches

FOR i = 1 TO numOfLines%
    lineRepeats% = Repeat%(pattern$, inputLines$(i))
    totalRepeats% = totalRepeats% + lineRepeats%
NEXT i

' display lines entered by the user...

PRINT "You entered the following lines:"
PRINT
FOR i = 1 TO numOfLines%
    PRINT inputLines$(i)
NEXT i

' and the total number of matches

PRINT
PRINT "The pattern '"; pattern$; "' appears"; totalRepeats%; "times"

END

SUB GetText (strArray$(), count%)

' The GetText subprogram fills the strArray$() array with text
'   entered at the keyboard.  The number of lines that can be
'   entered is determined by the global constant MAXLINES%.
'   Both strArray$() and count% (the number of lines actually
'   entered) are returned to the main program.

PRINT "Enter up to"; MAXLINES%; "lines of text; to end, ";
PRINT "press Enter on a new line."
PRINT
count% = 0
   
DO
    LINE INPUT "-> "; inLine$  ' get line from user
    IF (inLine$ <> "") THEN    ' if line is not blank, copy it
        count% = count% + 1    '   to the strArray$() array
        strArray$(count%) = inLine$
    END IF
' loop until count% = MAXLINES% or an empty line is received
LOOP WHILE (count% < MAXLINES%) AND (inLine$ <> "")

END SUB

FUNCTION Repeat% (search$, base$)
 
' The Repeat% function returns the number of times a search string
'   is found in a base string.

searchLength% = LEN(search$)  ' determine length of search string
baseLength% = LEN(base$)      ' determine length of base string
currentChar% = 1              ' character offset in base string
num% = 0                      ' running total of matches found in base

' loop until entire string is processed or INSTR returns a 0

WHILE (currentChar% <= baseLength%) AND (currentChar% <> 0)
    currentChar% = INSTR(currentChar%, base$, search$)
    IF (currentChar% <> 0) THEN  ' if not zero, a match was found
        num% = num% + 1          ' increment number of matches
        ' new offset equals current offset plus search-string length
        currentChar% = currentChar% + searchLength%
    END IF
WEND

Repeat% = num%                ' return total number of matches

END FUNCTION

