LessonsBeginner: First stepsLesson 16

Searching text

Find where something is with offset, wordOffset, itemOffset and lineOffset, and count how often it appears.

  • Beginner
  • Lesson 16 of 83
  • About 7 minutes
  • 4 examples

Where is it?

contains tells you whether something is there. offset tells you where: the number of the character it starts at, or 0 when it is not there at all.

ExampleRun it in the playground
put "the cat sat on the mat" into tText
put offset("sat", tText)
put offset("dog", tText)
put char offset("on", tText) to -1 of tText
Output
9
0
on the mat

Which word, item or line?

The other offsets count in chunks, which is usually what you want for a list: the number of the word, item or line that holds the text.

ExampleRun it in the playground
put wordOffset("on", "the cat sat on the mat")
put itemOffset("blue", "red,green,blue")
put "apple" & return & "fig" & return & "kiwi" into tFruit
put lineOffset("fig", tFruit)
put lineOffset("pear", tFruit)
Output
4
3
2
0

How many times?

To count every copy, look again from just after the last one found. offset's third value says how many characters to skip, and the answer is counted from there.

ExampleRun it in the playground
put "she sells sea shells by the sea shore" into tText
put 0 into tCount
put 0 into tSkip
repeat
   put offset("se", tText, tSkip) into tFound
   if tFound is 0 then exit repeat
   add 1 to tCount
   add tFound to tSkip
end repeat
put tCount
Output
3

For whole words there is an easier way: loop over the words and compare each one, as in Repeat for each.

Try it yourself

An email address is ada@example.com. Use offset to put the part before the @ and the part after it.

Show a solution
ExampleRun it in the playground
put "ada@example.com" into tEmail
put offset("@", tEmail) into tAt
put char 1 to tAt - 1 of tEmail
put char tAt + 1 to -1 of tEmail
Output
ada
example.com

Words in this lesson

Each one finds every lesson that uses it. The Dictionary has the whole story of each, with its syntax and more examples.