Help with splitting a string into a character array.

160 visualizaciones (últimos 30 días)
Benjamin Carpenter
Benjamin Carpenter el 5 de Nov. de 2017
Editada: Stephen23 el 7 de Nov. de 2021
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
word=datasample(wordbank,1)
%identify length of word
wordlength=strlength(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 comentario
Fady Samann
Fady Samann el 5 de Sept. de 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 ';
c=1;
for i=1:length(s)
if s(i)~=' '
new_s(c)=s(i);
c=c+1;
end
end

Iniciar sesión para comentar.

Respuesta aceptada

Mischa Kim
Mischa Kim el 5 de Nov. de 2017
Editada: Mischa Kim el 5 de Nov. de 2017
You could use
s = 'Potato';
t = num2cell(s)
t =
1×6 cell array
{'P'} {'o'} {'t'} {'a'} {'t'} {'o'}
  3 comentarios
Akash Yadav
Akash Yadav el 7 de Nov. de 2021
isn't num2cell or num2string is used on a number array to convert it to string or cell array? what explains the working of num2cell on a string?
Stephen23
Stephen23 el 7 de Nov. de 2021
Editada: Stephen23 el 7 de Nov. de 2021
"isn't num2cell or num2string is used on a number array to convert it to string or cell array?"
No, NUM2CELL splits the elements of the input array into cells of a cell array. It does not "convert" anything: all of the original data still exists with its original class, just (in general) in more but smaller (e.g. scalar) arrays than beforehand.
"what explains the working of num2cell on a string?"
NUM2CELL operates the same regardless of the input class (this is clearly documented in the NUM2CELL documentation, where it lists all of the permitted input classes):
str = ["hello","world"]
str = 1×2 string array
"hello" "world"
out = num2cell(str)
out = 1×2 cell array
{["hello"]} {["world"]}
Storing scalar strings in a cell array should be avoided.
PS: the name is likely a relic of when MATLAB was young and only supported numeric arrays.
PPS: NUM2STRING is not a MATLAB function:
num2string(pi)
Unrecognized function or variable 'num2string'.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by