Pig Latin Converter Function
显示 更早的评论
Hello all,
I am trying to write a function which takes a string as input and converts it to Pig Latin string. For example, 'pig latin in matlab' would become 'igpay atinlay inay atlabmay'. So everything before the first vowel is shifted to the end of the word and following by 'ay'.
I know that I can use find to find the first vowel in each word. But then how do I move the characters to the end of each word and append 'ay' to it?
Here is what I have so far:
function [ new_string ] = pig_latin( string )
each_word = [];
temp = '';
ay = 'ay';
words = strsplit(string,' ');
num_words = numel(words);
for j=1:num_words
temp = words{j};
vowel = temp(find(ismember(temp,'aeiou'),1,'first'))
vowel_loc = find(vowel,1,'first');
end
采纳的回答
更多回答(1 个)
Image Analyst
2016-11-25
How about this:
To call:
new_string = pig_latin('pig latin in matlab other')
Function declaration
function [new_string] = pig_latin( string )
new_string = '';
ay = 'ay';
words = strsplit(string,' ');
numWords = length(words);
for k = 1 : numWords
thisWord = words{k};
firstVowel = thisWord(find(ismember(thisWord,'aeiou'),1,'first'));
vowelLocation = strfind(thisWord, firstVowel);
if vowelLocation >= 2
% Start the new word at the vowel location.
newWord{k} = [thisWord(vowelLocation:end), thisWord(1:vowelLocation-1), ay, ' '];
else
% If word starts with a vowel, just add 'ay'.
newWord{k} = [thisWord, ay, ' '];
end
end
% celldisp(newWord);
% String cells together to form the output character array.
new_string = [newWord{:}];
Shows in command window:
new_string =
igpay atinlay inay atlabmay otheray
2 个评论
Scott
2016-11-25
Image Analyst
2016-11-25
You're welcome. I tried to keep it somewhat simple and straightforward, and on your level and similar to your existing code. Maybe you could at least "Vote" for my answer.
类别
在 帮助中心 和 File Exchange 中查找有关 Characters and Strings 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!