How to replace only a single instance of a substring?
3 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!