简体   繁体   中英

Vectorize Matlab/Octave code for string operation

How do I vectorize the following Matlab/Octave code-

sentence='The quick brown fox';
l=findstr(sentence,' ');% One blank space
w=l(1);
first=sentence(1:w-1);
last=sentence(w:end);

I can combine the last two statements into one statement. Is there anything that can be done to convert the last four statements into one statement?

strtok will do what you're after.

>> [first, last] = strtok (sentence, ' ')
first = The
last =  quick brown fox

PS: Given the wording in your question, I feel compelled to point out that "one-liners" and "vectorisation" are two completely unrelated concepts.

You might consider using strsplit for extracting all the words in the sentence:

sentence='The quick brown fox';
words = strsplit(sentence, ' ');
first = words{1};
last = words{end};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM