MATLAB Answers

strtok not working with certain char array!! Help

1 view (last 30 days)
Rimmi Dhammi
Rimmi Dhammi on 27 Nov 2019
Hi I am attempting this code to break a string and add random char at a specific place.
L = input('Please enter the number of steps:')
message = input('Please enter your message:')
a = randi([double('a'), double('z')],1,L); % i use L to find my ranadom char length
random_str = char(a);
disp(random_str);
encrypt = '';
word = '';
while ~isempty(message)
[word, message] = strtok(message,message(2));
encrypt = strcat(encrypt,word,random_str);
end
I chose message as 'darkknight' and the program terminates at night (after k) and shows this information. As soon as it encounters same characters, it stops working.
[ word, message ] = strtok(message,message(2))
word =
'night'
message =
0×0 empty cha
Please someone help explain this. Thank you.

  0 Comments

Sign in to comment.

Answers (1)

Divya Yerraguntla
Divya Yerraguntla on 5 Feb 2020
Hi Rimmi,
I feel strtok s working as intended here. In your case when the message becomes 'kknight' the delimiter becomes 'k'(message(2)) which is also the first two letters of the message. Since strtok ignores the leading delimiters the variable word becomes 'night' and now since there is nothing left the variable message becomes empty.
Also, I am assuming you wish to add a random string after each letter of the input message.
The below code could help achieve the same:
L = input('Please enter the number of steps:')
message = input('Please enter your message:')
a = randi([double('a'), double('z')],1,L); % i use L to find my ranadom char length
random_str = char(a);
disp(random_str);
encrypt = '';
word = '';
for i=1:length(message)
encrypt = strcat(encrypt, message(i), random_str);
end
Hope it helps!

  0 Comments

Sign in to comment.

Sign in to answer this question.


Translated by