c-Pig拉丁函数输出错误



我正在编写一个函数,将单词转换为pillatin。然而,我得到了错误的输出,我不确定我做错了什么。这是我下面的代码。在某些单词上,它只是返回原来未更改的单词。也许我做这件事的方式不对。我很感激你的帮助。

char* convertToPigLatin(char* engStr, char* pLatinStr)
{
int length = 0;
char rSuffix[10];
char vowels[6] = "aeiou";
int i = 0;
while (engStr[length] != '')
{
length++;
}//setting int length equal to the length of the input string. 

while (i < length)
{
for (int j = 0; j < 6; j++)
{
//checking if the lead character is a consonant
if (engStr[0] != vowels[j])
{
rSuffix[j] =  '-';
rSuffix[j+1] = engStr[0];
}
//checking if there is a string of consonants
else if ((i != 0)&&(engStr[i] != vowels[j]))
{
rSuffix[j] = engStr[i];
}
//appending ay to consonant leading string
else if (engStr[i] == vowels[j])
{
rSuffix[j] = 'a';
rSuffix[j + 1] = 'y';
rSuffix[j + 2] = '';
strcat(engStr, rSuffix);
}
//string starting with vowel 
else if (engStr[0] == vowels[j])
{
rSuffix[j] = '-';
rSuffix[j + 1] = 'w';
rSuffix[j + 2] = 'a';
rSuffix[j + 3] = 'y';
rSuffix[j + 4] = '';
strcat(engStr, rSuffix);
}
}//for loop that goes thru the vowel array
i++;
}//while loop to go through the input string
for (int k = 0; k < 25; k++)
{
pLatinStr[k] = engStr[k];
}
return pLatinStr;
}

这是一个赋值,所以函数头需要这样。

我不能低估你的算法,主要是为了知道你是否有元音,你必须将一个字母与所有可能的元音进行比较,而不是为每个可能的元音做所有的事情

以下https://en.wikipedia.org/wiki/Pig_Latin在末尾添加"ay"(而不是"way"或"yay"等(一种可能的方法是:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char* convertToPigLatin(char* engStr, char* pLatinStr)
{
const char vowels[] = "aeiou";
if (! engStr[0])
/* empty string, not in pig latin def, decide to put ay */
strcpy(pLatinStr, "ay");
else if (strchr(vowels, engStr[0]) != NULL) {
/* starts by a vowels */
strcpy(pLatinStr, engStr);
strcat(pLatinStr, "ay");
}
else {
/* search first vowel */
char * p = engStr + 1;
while (*p && (strchr(vowels, *p) == NULL))
p += 1;
if (! *p)
/* no vowel, not in pig latin def, decide to let word unchanged */
strcpy(pLatinStr, engStr);
else {
size_t ln = strlen(p);
strcpy(pLatinStr, p);
strncpy(pLatinStr + ln, engStr, p - engStr);
strcpy(pLatinStr + ln + (p  - engStr), "ay");
}
}
return pLatinStr;
}
int main(int argc, char ** argv)
{
if (argc == 2) {
char * p = malloc(strlen(argv[1]) + 3);
printf("'%s'n", convertToPigLatin(argv[1], p));
free(p);
}
else
fprintf(stderr, "usage : %s <word>n", *argv);
return 0;
}

当然convertToPigLatin假设第二个自变量足够大

编译和执行:

pi@raspberrypi:/tmp $ gcc -g -Wall p.c
pi@raspberrypi:/tmp $ ./a.out ste
'estay'
pi@raspberrypi:/tmp $ ./a.out aze
'azeay'
pi@raspberrypi:/tmp $ ./a.out mommy
'ommymay'
pi@raspberrypi:/tmp $ ./a.out cf
'cf'
pi@raspberrypi:/tmp $ ./a.out ""
'ay'
pi@raspberrypi:/tmp $ 

最新更新