Replace multiple substrings within a string
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (2)
Stephen23
el 13 de En. de 2018
Editada: Stephen23
el 13 de En. de 2018
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
0 comentarios
Roy Kadesh
el 13 de En. de 2018
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
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!