Replace multiple substrings within a string

I have a string of letters where i want to replace every A with 'BRARB' and every B with 'ALBLA'. I want to do this so that the Bs in 'BRARB' that was replaced by A in the current iteration, are not changed into 'ALBLA'. In other words,
function X=LindIter(N)
X='A';
for i=1:N
%if a letter in the string i A, replace it with BRARB, if it is B, replace with ALBLA.
X=strrep(X, 'A', 'BRARB');
end
As the code is now, it only replaces A with BRARB. The output, if N=1 should be BRARB, and if N=2 it should be ALBLARBRARBRALBLA

답변 (2개)

Stephen23
Stephen23 2018년 1월 13일
편집: Stephen23 2018년 1월 13일

2 개 추천

Method one: for loop and indexing:
S = 'A'
for k = 1:3
C = num2cell(S);
C(S=='A') = {'BRARB'};
C(S=='B') = {'ALBLA'};
S = [C{:}]
end
Giving:
S = A
S = BRARB
S = ALBLARBRARBRALBLA
S = BRARBLALBLALBRARBRALBLARBRARBRALBLARBRARBLALBLALBRARB
Method two: in one line using regexprep, arrayfun, and cell2mat:
>> fun = @(s)cell2mat(arrayfun(@(c)regexprep(c,{'A','(?<!R)B(?!R)'},{'BRARB','ALBLA'}),s,'uni',0));
>> S = 'A';
>> S = fun(S)
S = BRARB
>> S = fun(S)
S = ALBLARBRARBRALBLA
>> S = fun(S)
S = BRARBLALBLALBRARBRALBLARBRARBRALBLARBRARBLALBLALBRARB
...etc
Roy Kadesh
Roy Kadesh 2018년 1월 13일

0 개 추천

function X=LindIter(N)
X='A';
for i=1:N
%replace A with BRARB, replace B with ALBLA.
X(X=='A')='1';
X(X=='B')='2';
X=strrep(X, '1', 'BRARB');
X=strrep(X, '2', 'ALBLA');
end

댓글 수: 4

Guillaume
Guillaume 2018년 1월 13일
This will of course fails if '1' or '2' is present in the original string. You could of course use any other character guaranteed not to be present in the original string, if one exist (with arbitrary input there's isn't such a guarantee) but why bother with the unneeded replacement step. Just query the position and use that.
Roy Kadesh
Roy Kadesh 2018년 1월 13일
The problem with using position, is that you are replacing it with a longer array, and X(1)='BRARB'; will of course return an error. So how would you use a queried position?
Guillaume
Guillaume 2018년 1월 15일
Well, yes, you can't use simple indexing and have to do some splitting and reconcatenation instead, but it will be a lot more realiable.
Stephen23
Stephen23 2018년 1월 15일
"So how would you use a queried position?"
See the first method in my answer.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2018년 1월 13일

댓글:

2018년 1월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by