How to replace only a single instance of a substring?

조회 수: 20 (최근 30일)
John Doe
John Doe 2018년 3월 25일
편집: John Doe 2018년 3월 25일
Hi everybody,
for an assignment, I am supposed to turn a user inputted string into an "encrypted" message; My program is heavily dependent on the 'replace' function and my problem is that since I am using a loop with an iteration of 1:length(user_inputted_str) when it comes to words with repeated letters such as "hello", 'replace' will replace all 'l's with the corresponding encryption letter and then when the next iteration of the loop occurs, it replaces it again.
TL;DR Is there a way to replace only one instance of the substring using the strrep function? if not, I am open to other suggeestions.
Thank you so much
Code below:
inp = input('please input string to be converted: ', 's');
for i = 1:length(inp)
disp(inp(1,i))
switch inp(1,i)
case('a')
inp = replace(inp, inp(1,i),'n')
case('b')
inp = replace(inp, inp(1,i),'o')
case('c')
inp = replace(inp, inp(1,i),'p')
case('d')
inp = replace(inp, inp(1,i),'q')
case('e')
inp = replace(inp, inp(1,i),'r')
case('f')
inp = replace(inp, inp(1,i),'s')
case('g')
inp = replace(inp, inp(1,i),'t')
case('h')
inp = replace(inp, inp(1,i),'u')
case('i')
inp = replace(inp, inp(1,i),'v')
case('j')
inp = replace(inp, inp(1,i),'w')
case('k')
inp = replace(inp, inp(1,i),'x')
case('l')
inp = replace(inp, inp(1,i),'y')
case('m')
inp = replace(inp, inp(1,i),'z')
case('o')
inp = replace(inp, inp(1,i),'b')
case('p')
inp = replace(inp, inp(1,i),'c')
case('q')
inp = replace(inp, inp(1,i),'d')
case('r')
inp = replace(inp, inp(1,i),'e')
case('s')
inp = replace(inp, inp(1,i),'f')
case('t')
inp = replace(inp, inp(1,i),'g')
case('u')
inp = replace(inp, inp(1,i),'h')
case('v')
inp = replace(inp, inp(1,i),'i')
case('w')
inp = replace(inp, inp(1,i),'j')
case('x')
inp = replace(inp, inp(1,i),'k')
case('y')
inp = replace(inp, inp(1,i),'l')
case('z')
inp = replace(inp, inp(1,i),'m')
end
end

채택된 답변

Walter Roberson
Walter Roberson 2018년 3월 25일
Lines such as
inp = replace(inp, inp(1,i),'n')
should be
inp(1,i) = 'n';
This only affects a single location, and prevents positions from being changed twice. With your existing code, suppose your text started with 'a' and got replaced by 'n'. Suppose there was also an 'n' in the input. Then when you go to work on that 'n' on input and you go to replace the first 'n' with 'a', you would end up replacing the 'n' that you had generated from the 'a' . Your code should not be replacing inside anything it has already replaced.
  댓글 수: 1
John Doe
John Doe 2018년 3월 25일
Oh my god, I am an idiot. Thank you so much Walter!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by