Replace a single character with a new line in a string

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

>> 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

Thank you, that makes so much sense. My only query is: what if you had another 'w' in the sentence, that would then repeat the new line for each repeating 'w' ,when i would only want it to be individual to that particular index?
NB: one big difference between the two solutions -- the regexprep solution inserts a newline character into the returned string which is still one string:
>> regexprep(s,'w\s*','\n')
ans =
'hello there ho
are you today'
>> whos ans
Name Size Bytes Class Attributes
ans 1x28 56 char
>>
whereas the split solution returns an array...
"...that would then repeat the new line for each repeating 'w"
Try it and see:
>> str = 'many words will wait with worms';
>> regexprep(str,'w','\n')
ans = many
ords
ill
ait
ith
orms
>>
"when i would only want it to be individual to that particular index?
Then you can just replace the character at that index:
str(idx) = sprintf('\n');
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)

>> 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

Asked:

on 19 Apr 2020

Commented:

dpb
on 19 Apr 2020

Community Treasure Hunt

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

Start Hunting!