Last active
November 25, 2021 11:34
-
-
Save rodion-m/841ef515be8bfc2fbe1e05e40ad9dc63 to your computer and use it in GitHub Desktop.
Russian numbers spelling with words
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| namespace Proj | |
| { | |
| public static class RuSpellingExtensions | |
| { | |
| private static readonly Dictionary<string, string[]> spellDb = new Dictionary<string, string[]>() | |
| { | |
| //1 2 10 | |
| { "заказ", new[] { "заказа", "заказов" } }, | |
| { "раз", new[] { "раза", "раз" } }, | |
| { "день", new[] { "дня", "дней" } }, | |
| { "час", new[] { "часа", "часов" } }, | |
| { "клиент", new[] { "клиента", "клиентов" } }, | |
| { "товар", new[] { "товара", "товаров" } }, | |
| { "платеж", new[] { "платежа", "платежей" } }, | |
| { "год", new[] { "года", "лет" } }, | |
| //1 2 10 | |
| }; | |
| /// <summary> | |
| /// Склоняет заданное слово в соответствии с числом. Склонения берутся из базы выше. | |
| /// Важно: всегда возвращает результат в нижнем регистре. | |
| /// </summary> | |
| /// <example> | |
| /// 5.Spell("заказ") вернет "5 заказов" | |
| /// 155.Spell("год") вернет "155 лет" | |
| /// 21.Spell("год") вернет "21 год" | |
| /// </example> | |
| public static bool TrySpell(this long num, string word, out string spell) | |
| { | |
| if (word == null) throw new ArgumentNullException(nameof(word)); | |
| spell = null; | |
| var strNum = num.ToString(); | |
| var lastNum = long.Parse(strNum.Substring(strNum.Length - 1)); | |
| var lastTwoNum = (num > 10) ? long.Parse(strNum.Substring(strNum.Length - 2)) : 0; | |
| if (spellDb.TryGetValue(word.ToLowerInvariant(), out var rules)) | |
| { | |
| if ((lastTwoNum >= 10 && lastTwoNum <= 14) || lastNum == 0 || (lastNum >= 5 && lastNum <= 9)) | |
| spell = rules[1]; | |
| else if (lastNum == 1) | |
| spell = word; | |
| else /*in 2..4*/ | |
| spell = rules[0]; | |
| } | |
| if (spell != null) spell = $"{num} {spell}"; | |
| return spell != null; | |
| } | |
| public static bool TrySpell(this int num, string word, out string spell) => | |
| ((long)num).TrySpell(word, out spell); | |
| public static string Spell(this int num, string word) | |
| { | |
| if (num.TrySpell(word, out var spell)) | |
| return spell; | |
| else | |
| throw new NotImplementedException(nameof(word)); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment