Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Buffers;
- using System.Globalization;
- namespace LanguageGame
- {
- public static class Translator
- {
- /// <summary>
- /// Translates from English to Pig Latin. Pig Latin obeys a few simple following rules:
- /// - if word starts with vowel sounds, the vowel is left alone, and most commonly 'yay' is added to the end;
- /// - if word starts with consonant sounds or consonant clusters, all letters before the initial vowel are
- /// placed at the end of the word sequence. Then, "ay" is added.
- /// Note: If a word begins with a capital letter, then its translation also begins with a capital letter,
- /// if it starts with a lowercase letter, then its translation will also begin with a lowercase letter.
- /// </summary>
- /// <param name="phrase">Source phrase.</param>
- /// <returns>Phrase in Pig Latin.</returns>
- /// <exception cref="ArgumentException">Thrown if phrase is null or empty.</exception>
- /// <example>
- /// "apple" -> "appleyay"
- /// "Eat" -> "Eatyay"
- /// "explain" -> "explainyay"
- /// "Smile" -> "Ilesmay"
- /// "Glove" -> "Oveglay"
- /// </example>
- public static string TranslateToPigLatin(string phrase)
- {
- int position = 0;
- int endOfWord = EndOfWord(phrase, position);
- string result = string.Empty;
- do
- {
- result += ToPigWord(phrase[position..endOfWord]);
- position = IndexOfLetter(phrase, endOfWord);
- result += phrase[endOfWord..position];
- endOfWord = EndOfWord(phrase, position);
- }
- while (position != -1 || endOfWord != -1);
- return result;
- }
- private static bool IsVowel(char symbol) => symbol is 'a' || symbol is 'A' ||
- symbol is 'o' || symbol is 'O' ||
- symbol is 'e' || symbol is 'E' ||
- symbol is 'i' || symbol is 'I' ||
- symbol is 'u' || symbol is 'U';
- private static string ToPigWord(string phrase)
- {
- if (IsVowel(phrase[0]))
- {
- return phrase + "yay";
- }
- int position = VowelFirstPosition(phrase);
- return char.IsUpper(phrase[0])
- ? char.ToUpper(phrase[position], CultureInfo.InvariantCulture) + phrase[(position + 1) ..] +
- char.ToLower(phrase[0], CultureInfo.InvariantCulture) + phrase[1..position] + "ay"
- : phrase[position..] + phrase[..position] + "ay";
- }
- private static int VowelFirstPosition(string phrase, int position = 0)
- {
- for (int i = position; i < phrase.Length; i++)
- {
- if (IsVowel(phrase[i]))
- {
- return i;
- }
- }
- return -1;
- }
- private static int EndOfWord(string phrase, int position = 0)
- {
- for (int i = position; i < phrase.Length; i++)
- {
- if (!char.IsLetter(phrase[i]))
- {
- return i;
- }
- }
- return -1;
- }
- private static int IndexOfLetter(string phrase, int position = 0)
- {
- for (int i = position; i < phrase.Length; i++)
- {
- if (char.IsLetter(phrase[i]))
- {
- return i;
- }
- }
- return -1;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement