要求:
- 如果单词中不含元音字母,不做任何翻译.
- 如果单词以元音字母开始,则翻译出的儿童黑话包括原单词加上其后缀way.
- 如果单词以辅音字母开始,提取辅音字符子串直到遇到第一个元音字母,移动收集的辅音字母到单词结尾,然后添加后缀ay.
分析:其主要功能是要找出单词中的元音字母及其下标.
代码如下:
#include <iostream>
#include <string>
#include <cctype>
#include <cstring>
using namespace std;
/*Function Prototypes */
string lineToPigLatin(string line);
string wordToPigLatin(string word);
int findFirstVowel(string word);
bool isVowel(char ch);
/* Main program */
int main(void)
{
cout << "This program translates English to Pig Latin." << endl;
string line;
cout << "Enter English text:";
getline(cin,line);
string translation = lineToPigLatin(line);
cout << "Pig Latin output: " << translation << endl;
cin.get();
return 0;
}
/**
* Function:lineToPigLatin
* Usage: string translation = lineToPigLatin(line);
* return: string
* -------------------------------------------------
* 2018-9-26
* */
string lineToPigLatin(string line)
{
string result;
int start = -1;
for(int i = 0;i < line.length();++i)
{
char ch = line[i];
if(isalpha(ch))
{
if(start == -1)
{
start = i;
}
}else{
if(start >= 0)
{
result += wordToPigLatin(line.substr(start,i - start));
start = -1;
}
result += ch; //添加空格
}
}
if (start >= 0)
{
result += wordToPigLatin(line.substr(start));
}
return result;
}
/**
* Function: wordToPigLatin
* Usage: string translation = wordToLatin(word);
* return: string
* ----------------------------------------------
* 2018-9-26
* */
string wordToPigLatin(string word)
{
int index = findFirstVowel(word);
if(index == -1)
{
return word;
}else if(index == 0)
{
return word + "way";
}else
{
string head = word.substr(0,index);
string tail = word.substr(index);
return tail + head + "ay";
}
}
/**
* Function: findFirstVowel
* Usage: int k = findFirstVowel(word);
* return: int
* ------------------------------------
* return the index position of the first vowel in word.
* 2018-9-26
* */
int findFirstVowel(string word)
{
for(int i = 0;i < word.length();++i)
{
if(isVowel(word[i])) return i;
}
return -1;
}
/**
* Function: isVowel
* Usage: if (isVowel(ch)) ...
* return: bool
* ---------------------------
* return ture: is vowel;return false: is not vowel
* 2018-9-26
* */
bool isVowel(char ch)
{
char vowel[] = {'a','e','i','o'};
for(int i = 0;i < strlen(vowel);++i)
{
if(vowel[i] == ch) return true;
}
return false;
}
本文由 giao创作, 采用 知识共享署名4.0 国际许可协议进行许可 本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名 原文地址:《C++实现儿童黑话》
最后一次更新于2018-12-24
0 条评论