spitting up a character

1 回表示 (過去 30 日間)
Christopher Beck
Christopher Beck 2019 年 3 月 7 日
回答済み: Daniel Dolan 2019 年 3 月 7 日
I want to split up any given number (as a character) with "," in such a way that if there is a 2 or a 6, it and the next digit are taken as a pair and put a "," around them.
e.g. '1357320676222345' would become '13573,20,67,62,22,345'
my attempts just end up just putting a lot of ',' around the first pair that meets this condition
I realise it has to do with the fact the character length keeps increasing with each itteration, but I don't know how to get around this problem.
clear
c = '1357320676222345'
L = length(c)
for i = 1:L
if c(i) == '2'
j = i
c = insertBefore(c,i,',')
c = insertAfter(c,i+2,',')
continue
end
if c(i) == '6'
j = i
c = insertBefore(c,i,',')
c = insertAfter(c,i+2,',')
continue
end
end

採用された回答

tmarske
tmarske 2019 年 3 月 7 日
Try doing it in two passes, one to add a comma before, another to add one after:
c = '1357320676222345'
c = regexprep(c, '([26]\d)', ',$1')
c = regexprep(c, '([26]\d)[^,]', '$1,')
The first regexprep adds a comma before each instance, the second adds one after, so long as there is not one already present.
Check that this is actually the behaviour you want (how '62' should be treated, whether you want commas at the beginning or end of the character sequence, etc.)

その他の回答 (1 件)

Daniel Dolan
Daniel Dolan 2019 年 3 月 7 日
How about htis?
clear
c = '1357320676222345';
L = length(c);
out=repmat('0',[1 3*L]);
i=1;
k=1;
while i < L
if (c(i) == '2') || (c(i) == '6')
out(k:k+3)=[',' c(i:i+1) ','];
k=k+4;
i=i+2;
else
out(k)=c(i);
k=k+1;
i=i+1;
end
end
out(k)=c(end);
c=out(1:k);
c=strrep(c,',,',',')

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by