You can make it a lot easier on yourself by using std::string from the standard library. Also, there's another rule you missed: a word starting with a vowel simply gets ‘-way’ appended. For example, ‘eagle’ becomes ‘eagleway’:
Code:
#include <cstring>
#include <string>
#include <iostream>
inline bool is_vowel(char ch) {
return strchr("aeiou", ch);
}
std::string con_PLatin(const std::string word) {
std::string lead, rest;
for (int i = 0; i < word.length(); ++i)
if (is_vowel(word[i])) {
lead = word.substr(0, i);
rest = word.substr(i, word.length());
break;
}
return rest + (lead.empty() ? "way" : lead + "ay");
}
If you want to be able to pass C-strings, just overload to convert:
Code:
const char* con_PLatin(const char* word) {
return con_PLatin(std::string(word)).c_str();
}
(Haskell:
Code:
import Data.List (break)
import System (getArgs, getProgName)
main = getArgs >>= doPigLatin
doPigLatin [] = do progName <- getProgName
putStrLn $ "Usage: " ++ progName ++ " <word>"
doPigLatin wrds = putStr . unlines . map pigLatin $ wrds
pigLatin word = let (lead, rest) = break isVowel word
in rest ++ (if lead == "" then "way" else lead ++ "ay")
where isVowel = (`elem` "aeiou")
)
Edit: surely there's some easy way to get rid of that annoying ‘const’ on the char* overload? Something like:
Code:
char *copy_string(const char* str) {
char ret[strlen(str)];
strcpy(ret, str);
return ret;
}
?
Further edit: aha — I found it:
Code:
char* con_PLatin(const char* word) {
return const_cast<char *>(con_PLatin(std::string(word)).c_str());
}
Since the resultant std::string is discarded, that should be safe, right?
Bookmarks