Pig Latin:一种自发明语言,将英文单词按如下规则转换:
如果单词以辅音开头,则把起始辅音字符串(直到第一个
元音字母的所有字母)从单词头移到单词尾,并在末尾加上ay,
如scram转换成Pig Latin单词就是amscray;如果单词以元音(a、e、i、o、u,包括大小写)开头,则加
后缀way,如is转换成Pig Latin单词就是isway。
要求使用自顶向下的方式编写程序,实现读入一行英文
(含多个单词、空格、标点符号),将该行英文转换成Pig Latin语言。
效果如下:
输入:What are you doing?
输出:atWhay areway ouyay oingday?
#include<iostream>
#include<stdio.h>
using namespace std;
inline int qchar(char c)
{
if(c>='A'&&c<='Z')c=c+'a'-'A';
if((c=='a')||(c=='e')||(c=='u')||(c=='i')||(c=='o'))return 1;
if(c>='a'&&c<='z')return 2;
if(c=='\n'||c==EOF)return 0;
return 3;
}
int main()
{
char c[1000],t;
int i,m;
while(1){
t=getchar();
if(!qchar(t))
break;
if(qchar(t)==3)
{
putchar(t);continue;
}
if(qchar(t)==1)
{
while((qchar(t)==1)||(qchar(t)==2))
{
putchar(t);
t=getchar();
}
cout<<"way";
if(!qchar(t))break;
cout<<t;
continue;
}
for(i=0;qchar(t)==2;i++)
{
c[i]=t;
t=getchar();
}
c[i]='\0';
while((qchar(t)==1)||(qchar(t)==2))
{
putchar(t);
t=getchar();
}
cout<<c<<"ay";
if(!qchar(t))break;
cout<<t;
}
return 0;
}
或
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
string lineToPigLatin(string line);
string wordToPigLatin(string word);
int findFirstVowel(string word);
bool isVowel(char ch);
int main()
{
string line;
getline(cin, line);
string translation = lineToPigLatin(line);
cout << translation << endl;
return 0;
}
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;
}
string wordToPigLatin(string word)
{
int vp = findFirstVowel(word);
if(vp == -1)
{
return word;
}
else if(vp ==0)
{
return word + "way";
}
else
{
string head = word.substr(0,vp);
string tail = word.substr(vp);
return tail + head + "ay";
}
}
int findFirstVowel(string word)
{
for(int i = 0; i <= word.length(); i++)
{
if(isVowel(word[i]))
return i;
}
return -1;
}
bool isVowel(char ch)
{
switch(ch)
{
case 'A': case 'E': case 'I': case'O': case 'U':
case 'a': case 'e': case 'i': case'o': case 'u':
return true;
default:
return false;
}
}