Home | Administração | Fórum | Livros | WWW | Diário | Tarefas | Alunos |
Este é um resumo da seção 3.3, p.123-138, do livro do Eric Roberts.
A função abaixo foi copiada (com algumas modificações) da figura 3-5, p.130, do livro de Eric Roberts.
typedef char *string; #include <stdlib.h> // preciso de malloc #include <string.h> // preciso de strlen etc. #include <ctype.h> // preciso de tolower string PigLatin( string word); string FindFirstVowel( string word); #define MaxWord 20 int main( void) { char word[MaxWord+1]; printf( "Enter a word with no more than %d letters: ", MaxWord); scanf( "%s", word); printf( "Pig Latin: %s\n", PigLatin( word)); return 0; } // Function: PigLatin // ------------------ // This function translates a word from English to Pig Latin. // The rules for forming Pig Latin words are as follows: // // o If the word begins with a vowel, add "way" to the // end of the word. // o If the word begins with a consonant, extract the // consonants up to the first vowel, move that substring // to the end of the word, and add "ay". // // Examples: Inglês PigLatin // ---------------------- // ash ashtray // structure ucturestray // pointer ointerpay // address addressway string PigLatin( string word) { string vp, pig; int wordLength; wordLength = strlen( word); vp = FindFirstVowel( word); if (vp == word) { wordLength += 3; } else if (vp != NULL) { wordLength += 2; } pig = malloc( wordLength * sizeof (char) + 1); if (vp == NULL) { strcpy( pig, word); } else if (vp == word) { strcpy( pig, word); strcat( pig, "way"); } else { strcpy( pig, vp); strncat( pig, word, vp - word); strcat( pig, "ay"); } return pig; } // The FindFirstVovel function returns the address of the // first vowel in word. If word does not contain a vowel, // the function returns NULL. string FindFirstVowel( string word) { char *cp; for (cp = word; *cp != '\0'; cp++) { char c = tolower( *cp); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') return cp; } return NULL; }
char *src = "Alo"; char *dst; strcpy( dst, src);
Eric Roberts escreveu uma biblioteca de manipulação de cadeias que é mais amigável que a biblioteca padrão pois faz as necessárias alocações dinâmicas internamente. O arquivo-interface dessa biblioteca é strlib.h e a correspondente implementação está em strlib.c.
Veja como a função PigLatin fica mais simples e mais legível se usarmos as funções da biblioteca de Eric Roberts:
#include "strlib.h" string PigLatin( string word) { int vp; string head, tail; vp = FindFirstVowel( word); if (vp == -1) { return word; } else if (vp == 0) { return Concat( word, "way"); } else { head = SubString( word, 0, vp - 1); tail = SubString( word, vp, StringLength( word) - 1); return Concat( tail, Concat( head, "ay")); } }