How to replace only a single instance of a substring?

18 vues (au cours des 30 derniers jours)
John Doe
John Doe le 25 Mar 2018
Modifié(e) : John Doe le 25 Mar 2018
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

Réponse acceptée

Walter Roberson
Walter Roberson le 25 Mar 2018
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 commentaire
John Doe
John Doe le 25 Mar 2018
Oh my god, I am an idiot. Thank you so much Walter!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Conversion 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