Skip to content

Instantly share code, notes, and snippets.

@Atlas7
Last active April 21, 2017 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Atlas7/91e9fc2900094ff18f73b683a1df0343 to your computer and use it in GitHub Desktop.
Save Atlas7/91e9fc2900094ff18f73b683a1df0343 to your computer and use it in GitHub Desktop.
Octave - how to scan through words in a long sentence

In Octave, the string manipulation function strtok() can be very handy for scanning through words in a long sentence.

In the following example, we have a sentence:

'hello world how are you'

Assuming all words are separated by a white space, we can repeat this command to extract (1) the word string tok and the remaining sentence s.

Concretely, run the following in an octave command line interface (CLI):

octave:93> s = 'hello world how are you'
s = hello world how are you
octave:94> [tok, s] = strtok(s)
tok = hello
s =  world how are you

octave:95> [tok, s] = strtok(s)
tok = world
s =  how are you

octave:96> [tok, s] = strtok(s)
tok = how
s =  are you

octave:97> [tok, s] = strtok(s)
tok = are
s =  you

octave:98> [tok, s] = strtok(s)
tok = you
s = 

octave:99> [tok, s] = strtok(s)
tok = 
s = 

octave:100> 

We can easily do a while loop like this to scan through the whole thing:

s = 'hello world how are you';
while ~isempty(s),
  [tok, s] = strtok(s);
  fprintf('\n======\n');
  disp(tok);
  disp(s);
end;

output:

======
hello
 world how are you

======
world
 how are you

======
how
 are you

======
are
 you

======
you

octave:115> 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment