我有一个文本,我想把它变成一个分隔字母的数组。例如。:
'hello world' → ['h','e','l','l','o',' ','w','o','r','l','d']
谢谢。
ps MATLAB 2013a
Your original question does not make much sense; a string already is an array of characters.
Building on the assumption the others here have taken (that you want a cell array of individual characters), there is this slightly shorter alternative:
>> num2cell('hello world')
ans =
'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'l' 'd'
Another way:
>> regexp('hello world', '.', 'match')
ans =
'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'l' 'd'
You can also take a look at strsplit
(introduced in R2013a or so)
num2cell
preserves the class of the input argument, as seen in the relevant section in num2cell
:
c = cell(size(a));
for i=1:numel(a)
c{i} = a(i);
end
The basics: under the hood, a string (== array of chars
) is essentially an array of 8-bit integers, interpreted a different way. Type 'hello world'+0
to see what I mean; you'll get the UTF-8 table values of the individual characters in an array of integers (well, double
s, but oh well).
在许多方面,字符串 'hello world' 是一个分隔的字母数组。也许您正在寻找一个元胞数组,其中每个元素都是一个标量字符
x = mat2cell('hello world', 1, ones(11, 1))
x =
'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'l' 'd'
据我了解,字符串本质上是一个字符数组,所以没有什么可做的:
>> str = 'hello world'
str = hello world
>> str(1)
ans = h
>> str(2)
ans = e
>> str(3)
ans = l