replace multiple characters in a string with different characters

144 vues (au cours des 30 derniers jours)
Tiasa Ghosh
Tiasa Ghosh le 9 Juil 2018
Commenté : Tiasa Ghosh le 10 Juil 2018
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 commentaires
OCDER
OCDER le 9 Juil 2018
Why don't you want to use strrep ?
Walter Roberson
Walter Roberson le 9 Juil 2018
Sounds like you might be looking for the equivalent of the unix command tr

Connectez-vous pour commenter.

Réponse acceptée

OCDER
OCDER le 9 Juil 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

Plus de réponses (2)

Rik
Rik le 9 Juil 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 le 9 Juil 2018
Modifié(e) : Rik le 9 Juil 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)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by