MATLAB Answers

Help with splitting a string into a character array.

233 views (last 30 days)
Let's say I have a string s='Potato'.
How would I split that up into an array so that it looks like t='P, o, t, a, t, o'?
I'm currently doing it like this:
%%Choose word
%identify length of word
sol = split(word,"")
The only problem with doing it this way is that there are two blank spots and the beginning and end of the character array. It looks like this when outputted:
"" "P" "o" "t" "a" "t" "o" ""
How can I split it so that the blank values at the beginning and end aren't there?

  1 Comment

Fady Samann
Fady Samann on 5 Sep 2020
the string is already an array of char. So, s(1) is 'P'. However, if you want to remove the blanks, you have to do it by a 'for' loop and test for blanks with 'if' condition.
s=' Potato ';
for i=1:length(s)
if s(i)~=' '

Sign in to comment.

Accepted Answer

Mischa Kim
Mischa Kim on 5 Nov 2017
Edited: Mischa Kim on 5 Nov 2017
You could use
s = 'Potato';
t = num2cell(s)
t =
1×6 cell array
{'P'} {'o'} {'t'} {'a'} {'t'} {'o'}

More Answers (0)

Community Treasure Hunt

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

Start Hunting!