Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- using System.Globalization;
- using System.Reflection.Metadata.Ecma335;
- using System.Text;
- using System.Xml;
- namespace TransformerToWords
- {
- /// <summary>
- /// Implements transformer class.
- /// </summary>
- public class Transformer
- {
- /// <summary>
- /// Transforms each element of source array into its 'word format'.
- /// </summary>
- /// <param name="source">Source array.</param>
- /// <returns>Array of 'word format' of elements of source array.</returns>
- /// <exception cref="ArgumentNullException">Thrown when array is null.</exception>
- /// <exception cref="ArgumentException">Thrown when array is empty.</exception>
- /// <example>
- /// new[] { 2.345, -0.0d, 0.0d, 0.1d } => { "Two point three four five", "Minus zero", "Zero", "Zero point one" }.
- /// </example>
- public string[] Transform(double[]? source)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source), "array is null");
- }
- if (source.Length == 0)
- {
- throw new ArgumentException("array length is zero", nameof(source));
- }
- string[] result = new string[source.Length];
- for (int i = 0; i < source.Length; i++)
- {
- result[i] = NumberToWord(source[i]);
- }
- return result;
- }
- private static string NumberToWord(double number)
- {
- switch (number)
- {
- case double.NaN:
- return "Not a Number";
- case double.Epsilon:
- return "Double Epsilon";
- case double.NegativeInfinity:
- return "Negative Infinity";
- case double.PositiveInfinity:
- return "Positive Infinity";
- }
- string stringNumber = number.ToString(CultureInfo.InvariantCulture);
- StringBuilder result = new StringBuilder();
- for (int i = 0; i < stringNumber.Length; i++)
- {
- result.Append(CharToWord(stringNumber[i]));
- }
- return char.ToUpper(result[1], CultureInfo.InvariantCulture) + result.ToString()[2..];
- }
- private static string? CharToWord(char digit) =>
- digit switch
- {
- '-' => " minus",
- '+' => " plus",
- '.' => " point",
- 'E' => " E",
- '0' => " zero",
- '1' => " one",
- '2' => " two",
- '3' => " three",
- '4' => " four",
- '5' => " five",
- '6' => " six",
- '7' => " seven",
- '8' => " eight",
- '9' => " nine",
- _ => null
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement