Combining string and numerical values
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi, I'm doing a review sheet (not for a grade), and I'm hitting a snag with combining string and character vectors. Here's my problem:
Write a function my_password that will receive a string or character vector with a message and create a password that alternates between the final letter of each word and length of each word.
I've tried the following two functions, the first one only works if your in phrase is one word, and the second returns only a character vector:
function password=my_password(inphrase)
password= inphrase(end);
passnum= strlength(inphrase);
newpass= strcat(password, int2str(passnum))
end
function password = mypassword(inphrase);
rest = strtrim(char(inphrase));
password = '';
while ~isempty(rest)
[word, rest] = strtok(rest);
password = strcat(password,int2str(word));
end
end
3 commentaires
Stephen23
le 21 Avr 2020
>> str = 'I like MATLAB'
>> regexprep(str,'\s*(\w*)(\w)','$2${num2str(1+numel($1))}')
ans =
'I1e4B6'
Réponse acceptée
Ameer Hamza
le 21 Avr 2020
Try these two options
function newpass = my_password1(inphrase)
words = strsplit(inphrase, ' ');
last_char = cellfun(@(x) {x(end)}, words);
lens = cellfun(@(x) {num2str(numel(x))}, words);
X = cell(1,numel(words));
X(1:2:end) = last_char(1:2:end);
X(2:2:end) = lens(2:2:end);
newpass = strjoin(X, '');
end
function newpass = my_password2(inphrase)
words = strsplit(inphrase, ' ');
last_char = cellfun(@(x) {x(end)}, words);
lens = cellfun(@(x) {num2str(numel(x))}, words);
newpass = strjoin(strcat(last_char, lens), '');
end
Test:
my_password1('A quick brown fox')
ans =
'A5n3'
my_password2('A quick brown fox')
ans =
'A1k5n5x3'
6 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Data Type Conversion 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!