简体   繁体   English

在MATLAB中对输入字符进行编码的功能

[英]Function to encoding input characters in MATLAB

I want to create a function that encrypts the input sentence. 我想创建一个输入句子进行加密的函数。 This encryption will replace the first letter of each word with the next letter in the ASCII table, and the second letter with the next, .... 这种加密会将每个单词的第一个字母替换为ASCII表中的下一个字母,并将第二个字母替换为下一个字母...。

So basically, the resulting output for abc def should be bcd efg . 因此,基本上, abc def的结果输出应为bcd efg However, when I run my function, the space will also be replaced, ie output will be bcd!efg . 但是,当我运行函数时,空格也将被替换,即输出将为bcd!efg Why is this so? 为什么会这样呢? Thanks. 谢谢。

Below is what I have written: 以下是我写的内容:

function out = encrypt(input)
ascii_encode=double(input);
line={ascii_encode};
counter=0;

for a=1:length(line)
    if line{a}==32
        counter=0;
    else
        counter=counter+1;
        line{a}=line{a}+counter;  
    end   
    line{a}=char(line{a});
end        
out=line;
end

You should be careful handling cells . 您应该小心处理单元

Try line{a} , line(a) , line(1){a} , to understand how they work. 尝试使用line{a}line(a)line(1){a}来了解它们的工作原理。

The code should be like this, 代码应该是这样的,

function out = encrypt(input)
ascii_encode = double(input);
line = {ascii_encode};
for a = 1 : length(line{1})
    if line{1}(a) == 32
       continue;
    end    
    line{1}(a) = line{1}(a) + 1;  
end        
line{1} = char(line{1});
out = line{1};
end

And there is no need for counter , you just have to jump when if is true . 而且不需要counterif true if ,您只需要跳就可以了。

Kamtal's answer is perfectly right. Kamtal的答案是完全正确的。 You assign your input to a cell and then you were not accessing an index in the cell value (which is still a char array), but the full cell value. 您指定您输入到单元格,然后你不访问单元格值的索引(这仍然是一个字符数组),但完整的单元格的值。

Follow Kamtal answer if you still want to use cells type, and look at the cell documentation. 如果您仍然想使用单元格类型,请按照Kamtal的答案进行操作,并查看单元格文档。

Note that you could also benefit by Matlab vectorization capabilities, and simplify your function by: 请注意,您还可以从Matlab向量化功能中受益,并通过以下方式简化功能:

function out = encrypt(input)

charToKeep = ( input==' ' ) ; %// save position of character to keep
out = char(input+1) ;         %// apply the modification on the full string
out(charToKeep) = ' ' ;       %// replace the character we saved in their initial position

end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM