how to search for a sub string within a string in QBasic

2.6k views Asked by At

I am creating a simple chat programme in QBasic that will answer questions based on some specific key words present in the user input.therefore I need a way to search for a sub string (I.e. A specific word)within a string. So, please help me.

3

There are 3 answers

2
Marged On BEST ANSWER

To find out if a string contains a certain (sub-)string, you can do this:

text$ = "nonsense !"
IF INSTR( text$, "sense" ) >= 1 THEN
  PRINT "This text makes sense !"
END IF

And no, I was not able to test this, as a no longer have QBasic on my PC ;-) According to the link from the comment above >= 1 is ok

0
Dave On

I think INSTR is usually used as follows:

sent$ = "This is a sentence"

PRINT INSTR(1, sent$, "is")
PRINT INSTR(4, sent$, "is")
PRINT INSTR(1, sent$, "word")

the first PRINT command will print a '3' since the first location of "is" within the sentence is at position 3. (The 'is' in 'This')

the second PRINT command starts searching at position 4 (the 's' in 'This'), and so finds the "is" at position 6. So it will print '6'.

the third PRINT command will print a '0' since there is no instance of "word" in the sentence.

4
eoredson On

Counts the occurrences of a substring within a string.

T$ = "text to be searched and to be displayed"
S$ = "to"
l = 1
DO
    x = INSTR(l, T$, S$)
    IF x THEN
        n = n + 1
        l = x + LEN(S$)
    ELSE
        EXIT DO
    END IF
LOOP
PRINT "text '"; S$; "' matches"; n; "times."