none
Converting words to numbers ( 1 - 9) RRS feed

  • Question

  • Hi,

    so I'm trying to convert words to numbers.

    I'm having a tough time on how to convert words that have caps (ex one, One, OnE) to 1.

    The code so far is:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ProgrammingAssignment4
    {
        /// <summary>
        /// Converts words to digits
        /// </summary>
        public class Digitizer
        {
            #region Fields
    
            // declare your Dictionary field and create the Dictionary object for it here
            Dictionary<string, int> digitizer = new Dictionary<string, int>();
            #endregion
    
            #region Constructor
    
            /// <summary>
            /// Constructor
            /// </summary>
            public Digitizer()
            {
                // populate your dictionary field here
                string str0 = "zero";
                string lowerstr0 = str0.ToLower();
                digitizer.Add(lowerstr0, 0);
    
              
    
            }
    
            #endregion
    
            #region Public methods
    
            /// <summary>
            /// Converts the given word to the corresponding digit.
            /// If the word isn't a valid digit name, returns -1
            /// </summary>
            /// <param name="word">word to convert</param>
            /// <returns>corresponding digit or -1</returns>
            public int ConvertWordToDigit(string word)
            {
                // delete the code below and add your code
                return -1;
            }
    
            #endregion
        }
    }
    
    I've added "return -1;" cause I didn't want to deal with the error CS0161 when testing this. As of now any input returns -1.

    Sunday, November 22, 2020 10:19 AM

Answers

  • Hi YooOwnlt,

    Assuming you have already filled the data in the dictionary, this seems to be enough:

            public int ConvertWordToDigit(string word)
            {
                string key = word.ToLower();
                if (digitizer.ContainsKey(key))
                {
                    return digitizer[key];
                }
                return -1;
            }

    The range of numbers and filtering conditions can be modified as you wish.

    Best Regards,

    Timon


    "Visual C#" forum will be migrating to a new home on Microsoft Q&A ! We invite you to post new questions in the "Developing Universal Windows apps" forum’s new home on Microsoft Q&A ! For more information, please refer to the sticky post.

    • Marked as answer by YooOwnIt Thursday, November 26, 2020 11:12 PM
    Monday, November 23, 2020 5:38 AM

All replies

  • forgot to mention but for this project if I type anything other than  0 - 7, 9 ("Bob") then the console has to return -1. All the words should return the numbers in that range regardless of the caps.

    One of the hints/suggestions in the project is to use the "ConvertWordToDigit" method to deal with the caps but I have no idea on how to implement this here

    • Edited by YooOwnIt Sunday, November 22, 2020 10:29 AM
    Sunday, November 22, 2020 10:27 AM
  • If you prefer a case-insensitive dictionary, then check an example:

    Dictionary<string, int> d = new Dictionary<string, int>( StringComparer.CurrentCultureIgnoreCase );
    d.Add( "zero", 0 );
    d.Add( "nought", 0 );
    d.Add( "one", 1 );
    d.Add( "two", 2 );
    //...
    
    string text = "OnE";
    int number;
    if( d.TryGetValue( text, out number ) )
    {
       Console.WriteLine( "Text: {0}, Number: {1}", text, number );
    }
    else
    {
       Console.WriteLine( "Not found: {0}", text );
    }
    


    Sunday, November 22, 2020 4:25 PM
  • Hello,

    Here is a solution

    https://stackoverflow.com/questions/11278081/convert-words-string-to-int

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string[] words = new[] { "ZERO", "four", "seventy five" };
    
                foreach (var word in words)
                {
                    Console.WriteLine(Helpers.ToLong(word));
                }
    
                Console.ReadLine();
            }
        }
    
        static class Helpers
        {
            private static readonly Dictionary<string, long> NumberTable =
                new Dictionary<string, long>
                {
                    {"zero",0},{"one",1},{"two",2},{"three",3},{"four",4},
                    {"five",5},{"six",6},{"seven",7},{"eight",8},{"nine",9},
                    {"ten",10},{"eleven",11},{"twelve",12},{"thirteen",13},
                    {"fourteen",14},{"fifteen",15},{"sixteen",16},
                    {"seventeen",17},{"eighteen",18},{"nineteen",19},{"twenty",20},
                    {"thirty",30},{"forty",40},{"fifty",50},{"sixty",60},
                    {"seventy",70},{"eighty",80},{"ninety",90},{"hundred",100},
                    {"thousand",1000},{"million",1000000},{"billion",1000000000},
                    {"trillion",1000000000000},{"quadrillion",1000000000000000},
                    {"quintillion",1000000000000000000}
                };
    
            public static long ToLong(string numberString)
            {
                var numbers = Regex.Matches(numberString, @"\w+")
                    .Select(m => m.Value.ToLowerInvariant())
                    .Where(v => NumberTable.ContainsKey(v))
                    .Select(v => NumberTable[v]);
    
                long acc = 0, total = 0L;
                foreach (var n in numbers)
                {
                    if (n >= 1000)
                    {
                        total += (acc * n);
                        acc = 0;
                    }
                    else if (n >= 100)
                    {
                        acc *= n;
                    }
                    else acc += n;
                }
                return (total + acc) * (numberString.StartsWith("minus",
                    StringComparison.InvariantCultureIgnoreCase) ? -1 : 1);
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    My GitHub code samples
    GitHub page

    Sunday, November 22, 2020 6:56 PM
    Moderator
  • Hey,

    I forgot to paste the code from the other .cs file here, which the ConvertWordtoDigit method refers to

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ProgrammingAssignment4
    {
        // Don't change ANY of the code in this file; if you
        // do, you'll break the automated grader!
    
        /// <summary>
        /// Programming Assignment 4
        /// </summary>
        class Program
        {
            /// <summary>
            /// Tests the Digitizer class
            /// </summary>
            /// <param name="args">command-line args</param>
            static void Main(string[] args)
            {
                Digitizer digitizer = new Digitizer();
    
                // loop while there's more input
                string input = Console.ReadLine();
                while (input[0] != 'q')
                {
                    // convert word to digit and print
                    Console.WriteLine(digitizer.ConvertWordToDigit(input));
    
                    input = Console.ReadLine();
                }
            }
        }
    }
    

    That said I cannot remove the ConvertWordtoDigit method because the automated grader will reject and fail all the tests that it runs

    Sunday, November 22, 2020 11:03 PM
  • Hi YooOwnlt,

    Assuming you have already filled the data in the dictionary, this seems to be enough:

            public int ConvertWordToDigit(string word)
            {
                string key = word.ToLower();
                if (digitizer.ContainsKey(key))
                {
                    return digitizer[key];
                }
                return -1;
            }

    The range of numbers and filtering conditions can be modified as you wish.

    Best Regards,

    Timon


    "Visual C#" forum will be migrating to a new home on Microsoft Q&A ! We invite you to post new questions in the "Developing Universal Windows apps" forum’s new home on Microsoft Q&A ! For more information, please refer to the sticky post.

    • Marked as answer by YooOwnIt Thursday, November 26, 2020 11:12 PM
    Monday, November 23, 2020 5:38 AM
  • Hey,

    Thanks for the answer! For ref I've also found different solution with the same results

     public int ConvertWordToDigit(string word)
            {
                // delete the code below and add your code
                
                
                
    
                if (digitizer.TryGetValue(word, out int number))
                {
                    return number;
                
                }
                return -1;
            }

    Thursday, November 26, 2020 10:57 PM