strtok not working with certain char array!! Help

4 vues (au cours des 30 derniers jours)
R HULD
R HULD le 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.

Réponses (1)

Divya Yerraguntla
Divya Yerraguntla le 5 Fév 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!

Catégories

En savoir plus sur Programming 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