a2
This commit is contained in:
parent
42d81729ad
commit
9b3b2b5f39
6
a2/pig_latin.h
Normal file
6
a2/pig_latin.h
Normal file
@ -0,0 +1,6 @@
|
||||
#ifndef PIG_LATIN_H
|
||||
#define PIG_LATIN_H
|
||||
|
||||
char *translate(const char *phrase);
|
||||
|
||||
#endif
|
||||
72
a2/program.c
Normal file
72
a2/program.c
Normal file
@ -0,0 +1,72 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include "pig_latin.h"
|
||||
|
||||
static int is_vowel(char c) {
|
||||
return c=='a' || c=='e' || c=='i' || c=='o' || c=='u';
|
||||
}
|
||||
|
||||
static int is_consonant(char c) {
|
||||
return c >= 'a' && c <= 'z' && !is_vowel(c);
|
||||
}
|
||||
|
||||
static void translate_word(const char *word, char *buf) {
|
||||
int len = (int)strlen(word);
|
||||
|
||||
if (is_vowel(word[0]) ||
|
||||
(len >= 2 && word[0]=='x' && word[1]=='r') ||
|
||||
(len >= 2 && word[0]=='y' && word[1]=='t')) {
|
||||
sprintf(buf, "%say", word);
|
||||
return;
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
while (i < len && is_consonant(word[i]) && word[i] != 'y') {
|
||||
if (word[i] == 'q' && i + 1 < len && word[i+1] == 'u') break;
|
||||
i++;
|
||||
}
|
||||
|
||||
int split;
|
||||
|
||||
if (i < len - 1 && word[i] == 'q' && word[i+1] == 'u') {
|
||||
split = i + 2;
|
||||
}
|
||||
else if (i > 0 && i < len && word[i] == 'y') {
|
||||
split = i;
|
||||
}
|
||||
else {
|
||||
split = i > 0 ? i : 1;
|
||||
}
|
||||
|
||||
strncpy(buf, word + split, len - split);
|
||||
buf[len - split] = '\0';
|
||||
strncat(buf, word, split);
|
||||
strcat(buf, "ay");
|
||||
}
|
||||
|
||||
char *translate(const char *phrase) {
|
||||
if (!phrase) return NULL;
|
||||
|
||||
int plen = (int)strlen(phrase);
|
||||
char *result = malloc(plen * 2 + 16);
|
||||
if (!result) return NULL;
|
||||
result[0] = '\0';
|
||||
|
||||
char *copy = malloc(plen + 1);
|
||||
strcpy(copy, phrase);
|
||||
|
||||
char word_buf[512];
|
||||
int first = 1;
|
||||
char *token = strtok(copy, " ");
|
||||
while (token != NULL) {
|
||||
translate_word(token, word_buf);
|
||||
if (!first) strcat(result, " ");
|
||||
strcat(result, word_buf);
|
||||
first = 0;
|
||||
token = strtok(NULL, " ");
|
||||
}
|
||||
|
||||
free(copy);
|
||||
return result;
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user