replace multiple characters in a string with different characters

조회 수: 106 (최근 30일)
Tiasa Ghosh
Tiasa Ghosh 2018년 7월 9일
댓글: Tiasa Ghosh 2018년 7월 10일
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
OCDER
OCDER 2018년 7월 9일
Why don't you want to use strrep ?
Walter Roberson
Walter Roberson 2018년 7월 9일
Sounds like you might be looking for the equivalent of the unix command tr

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

채택된 답변

OCDER
OCDER 2018년 7월 9일
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

추가 답변 (2개)

Rik
Rik 2018년 7월 9일
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 2018년 7월 9일
편집: Rik 2018년 7월 9일
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)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by