replace multiple characters in a string with different characters

115 visualizaciones (últimos 30 días)
Hello! I am trying to replace multiple characters in a string using only one line of command. I am aware I can use regexprep to replace multiple characters with a single character like:
line = 'I am ready to use MATLAB';
replaced = regexprep(line,'[ru]','!');
this will give me: 'I am !eady to !se MATLAB'. But I want to replace the 'r' with a '!' and 'u' with '%'. So that the output will be like:
'I am !eady to %se MATLAB'
I do not want to use strrep for each replacement. How can I go about it? Thanks!
  2 comentarios
OCDER
OCDER el 9 de Jul. de 2018
Why don't you want to use strrep ?
Walter Roberson
Walter Roberson el 9 de Jul. de 2018
Sounds like you might be looking for the equivalent of the unix command tr

Iniciar sesión para comentar.

Respuesta aceptada

OCDER
OCDER el 9 de Jul. de 2018
Are you sure you don't want to use strrep?
strrep(strrep(line, 'r', '!'), 'u', '%')
I like to avoid the regexp functions if possible since there's a lot of sanity checks that goes on in those function, adding to delay. If its a simple 1-time call, then regexprep works fine.
line = 'I am ready to use MATLAB';
tic
for j = 1:100000
regexprep(line,{'r','u'},{'!','%'});
end
t1 = toc %0.683225 seconds
tic
for j = 1:100000
strrep(strrep(line, 'r', '!'), 'u', '%');
end
t2 = toc %0.215329 seconds

Más respuestas (2)

Rik
Rik el 9 de Jul. de 2018
You can enter cellstring inputs:
>>line = 'I am ready to use MATLAB';
>>replaced = regexprep(line,{'r','u'},{'!','%'});
replaced =
'I am !eady to %se MATLAB'

Rik
Rik el 9 de Jul. de 2018
Editada: Rik el 9 de Jul. de 2018
If you want to follow OCDER's advice, I would go for option 3. Using strrep in a loop is of course slower, but it allows much more flexibility in the number of replacements, and it is arguably more readable. (a lot of the extra time is spent in the call to numel)
line = 'I am ready to use MATLAB';
tic
for j = 1:100000
regexprep(line,{'r','u'},{'!','%'});
end
t1 = toc %0.8180 seconds
tic
for j = 1:100000
strrep(strrep(line, 'r', '!'), 'u', '%');
end
t2 = toc %0.2253 seconds
old={'r','u'};new={'!','%'};
tic
for j = 1:100000
for k=1:numel(old)
strrep(line, old{k}, new{k});
%line=strrep(line, old{k}, new{k});
end
end
t3 = toc %0.3066 seconds (0.2789 seconds with k=1:2)

Categorías

Más información sobre Get Started with MATLAB 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!

Translated by