Replace a single character with a new line in a string

15 views (last 30 days)
Hello there,
I have a string for example: 'hello there how are you today'
All i want to do is to index a character, remove that indexed character and then create a new line.
If i wanted to index the letter 'w' in 'how' for the example above, then it would perform the following:
'hello ho
are you today'
I know this seems weird, but i am doing something much more complicated so understanding how to do this in an easy way would really help with my undrstanding.
Thank you and would really appreciate some help.
Best wishes

Accepted Answer

Stephen23
Stephen23 on 19 Apr 2020
Edited: Stephen23 on 19 Apr 2020
>> str = 'hello there how are you today';
>> regexprep(str,'w','\n')
ans = hello there ho
are you today
And to remove that space character as well:
>> regexprep(str,'w\s*','\n')
ans = hello there ho
are you today
  5 Comments
dpb
dpb on 19 Apr 2020
Well, if that's what's wanted, then
>> strrep(str,'w',char(10))
ans =
'many
ords
ill
ait
ith
orms'
>>
>> all(regexprep(str,'w','\n')==strrep(str,'w',char(10)))
ans =
logical
1
>>

Sign in to comment.

More Answers (1)

dpb
dpb on 19 Apr 2020
>> s= 'hello there how are you today';
>> strip(split(s,'w')) % if the location is a known character...
ans =
2×1 cell array
{'hello there ho'}
{'are you today' }
>>
>> ix=strfind('w'); % if must find the delimiter location
>> s(ix)=char(0); % insert delimiter and same song...
>> strip(split(s,char(0)))
ans =
2×1 cell array
{'hello there ho'}
{'are you today' }
>>
With more specifics on the actual application, possibly better techniques including bringing regular expressions into play might come to the fore...this is the simple, high-level ML functions approach.

Categories

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

Community Treasure Hunt

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

Start Hunting!