这是针对 C 类的。我有以下方法。基本上,它需要一个单词和一个 newWord,如果原始单词以辅音开头,则通过将第一个字母移动到末尾(在结束标点符号之前)并在字符串中添加“ay”来创建 newWord。我所有的逻辑和案例都有效。我遇到的问题是,当我最后通过 char* newWord 并打印时,该值仍然是原始单词。另外,我自己定义了那些 isConsonant 和 isCapital 等方法。EndPunc 获取第一个结束标点的索引。
示例:word =“猫?!!” newWord = "Atc?!!"
word = "苹果" newWord = "appleay"
但是当我遍历 newWord 之后,它仍然是“Cat?!!” 或“苹果”。我究竟做错了什么?
#include <stdio.h>
//#include <string.h>
#define MAXLENGTH 31
char word[31] = "Aat!??!";
char newWord[31] = "";
char* w = word; char* n = newWord;
int isConsonant(char c) // return 1 if consonant, 0 if vowel, -1 if neither
{
int i = 0;
while(i < 33)
{
if(c == 'a'-i || c == 'e'-i || c == 'i'-i || c == 'o'-i || c == 'u'-i)
return 0;
i+=32;
}
if(c >= 65 && c <= 122) // its a letter
return 1;
else return -1;
}
int isCapital(char c)
{
if(c >= 97 && c <= 122) // lowerCase
return 0;
else return 1; // capital
}
int isPunctuation(char c)
{
if(c == '!' || c == ',' || c == '.' || c == '?' || c == ';' || c == ':')
return 1;
return 0;
}
int endPuncIndex(int wordLength, char* word)
{
int index = wordLength;
word += wordLength-1;
while(isPunctuation(*word--))
index--;
return index;
}
int pigLatin(char* word, char* newWord)
{
int length = 0;
char* tempWord = word;
while(*tempWord++ != '\0')
if(++length > MAXLENGTH)
return -1;
tempWord = tempWord-length-1;
int puncIndex = endPuncIndex(length, word); // get index of last punctuation, if none, index will be length of string
if(isConsonant(*word) == 1) // first letter is consonant
{
char firstLetter = *tempWord;
char secondLetter = *(++tempWord);
tempWord++;
if(isCapital(firstLetter))
{
firstLetter += 32; // makes it lowercase, will need to move this to the end
if(isCapital(secondLetter) == 0) // if second letter isn't capital, make it capital
secondLetter -= 32;
}
int start = 0;
newWord = &secondLetter;
newWord++;
while(start++ < puncIndex-2) // go up to punct index (or end of String if no ending punct)
{
newWord = tempWord++;
newWord++;
}
newWord = &firstLetter;
newWord++;
}
else // vowel, just copies the word letter for letter, no insert or shifting
{
int start = 0;
while(start++ < puncIndex) // go up to punct index (or end of String if no ending punct)
{
newWord = tempWord++;
newWord++;
}
}
// add "ay"
newWord = "a";
newWord++;
newWord = "y";
newWord++;
//then add remaining punctuation
while(puncIndex++ < length)
{
newWord = tempWord++;
newWord++;
}
newWord = newWord-(length);
while(*newWord != '\0')
printf("%c",*(newWord++));
return length+3;
}
int main()
{
pigLatin(w,n);
printf("\n");
system("PAUSE");
return 0;
}