MATLAB Answers

strtok is only using the first character of my delimiter instead of the full character vector

조회 수: 3(최근 30일)
Samuel Morstein
Samuel Morstein 26 Mar 2020
답변: Peng Li 26 Mar 2020
I am trying to use strtok to split a character vector using a character vector as my delimiter. However, MATLAB is only using the first character in the vector.
For example,
tok=strtok('Hello World','HAIR')
Returns
tok='ello World'
Instead of 'Hello World'

  댓글 수: 2

Guillaume
Guillaume 26 Mar 2020
I'm curious why you think that it should return 'Hello World' when H is one of the delimeter you specified.
Your strtok(xxx,'HAIR') explicitly tells matlab that H, A, I, or R is a delimiter.
Samuel Morstein
Samuel Morstein 26 Mar 2020
Oh I thought that it told matlab that the word itself was the delimiter not each individual character. How do I make it so that only HAIR is the delimiter and not H, A, I, or R?

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 26 Mar 2020
"How do I make it so that only HAIR is the delimiter and not H, A, I, or R?"
You can't do that with strtok. The simplest is to regexp with the 'split' option:
>> regexp('Hello World HAIR xyz HAIRdo', 'HAIR', 'split')
ans =
1×3 cell array
{'Hello World '} {' xyz '} {'do'}
Note: read the documentation of regexp as some characters such as .+- have special meaning.

  댓글 수: 0

댓글을 달려면 로그인하십시오.

추가 답변(1개)

Peng Li
Peng Li 26 Mar 2020
why don't you use strsplit instead?
>> a = strsplit('Hello World', 'HAIR')
a =
1×1 cell array
{'Hello World'}
>> a = strsplit('HHAIRello World', 'HAIR')
a =
1×2 cell array
{'H'} {'ello World'}

  댓글 수: 0

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by