How to replace only a single instance of a substring?
显示 更早的评论
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 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!