strtok not working with certain char array!! Help

4 ビュー (過去 30 日間)
R HULD
R HULD 2019 年 11 月 27 日
回答済み: Divya Yerraguntla 2020 年 2 月 5 日
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.

回答 (1 件)

Divya Yerraguntla
Divya Yerraguntla 2020 年 2 月 5 日
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!

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by