Delete words from a sentence (remove characters from a character array)

9 views (last 30 days)
I have been thinking for a long time how to solve this problem:
Write a function called jumping_the_shark that takes one
string (i.e., a row vector of type char) as an input argument (it does not
have to check the format of the input) and returns one string as an output argument.
If it is called like this, s2 = jumping_the_shark(s1) then s2 is
identical to s1 except that every occurrence of the string 'shark' has been
removed. Here is an example of the function in action:
>> s1
s1 =
The only good shark is a dead shark, excepting sand
sharks.
>> safe_to_go_in = jumping_the_shark(s1)
safe_to_go_in =
The only good is a dead excepting sand.
I have thought of suppressing the word shark based on an example in which I can change any letter of a string of characters, for example, if I want to change the letter s of the string s1 to the letter a, then one way to do it is
s1(s1=='s')='a'
based on this idea, what first occurs to me is to use
s1(s1=='shark')=''
but this does not work. Is there any way to do this in the same way or do you have to use something different? Another thing that occurs to me is to double (s1) and identify the elements (ventores) that correspond to the word shark and delete them from the vector double (s1) but I think this is complicated. What I can do? thank you.
There is a way to do this using erase but I would like to know more ways.

Answers (1)

Walter Roberson
Walter Roberson on 22 Mar 2019
Edited: Walter Roberson on 22 Mar 2019
  1. regexprep()
  2. strrep()
  3. strfind() to locate and then delete as appropriate
However! The examples do not match the text of the requirements. The requirements do not say anything about removing whitespace or punctuation, so the result for The only good shark is a dead shark, excepting sand sharks. should be The only good is a dead , excepting sand . -- notice the spacing and that the comma has not disappeared.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!