将数字转换为英语等效字符串形式

时间:2016-03-09 08:16:06

标签: vb.net

你能帮我制作一个程序,将输入数转换为由数字组成的英文等效字符串。例如,123代表"一个二三"和4017 by"四零一七"使用精选案例?

2 个答案:

答案 0 :(得分:0)

Choose功能在这种情况下派上用场。循环遍历数字中的每个数字,并将其等效字存储在StringBuilder

Function NumberToWords(ByVal number As Long) As String
    Dim words As New System.Text.StringBuilder
    For Each digit In number.ToString
        If digit = "0"c Then
            words.Append("zero")
        Else
            words.Append(Choose(CInt(digit.ToString), "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"))
        End If
        words.Append(" ")
    Next
    Return words.ToString.Trim
End Function

如果您正在寻找真正的数字到单词转换器,以下文章可能对您有所帮助: https://pradeep1210.wordpress.com/2014/09/09/number-to-words-converter/

答案 1 :(得分:0)

尝试这样的事情。

Imports System.Text

Module Module1

Private Words As Dictionary(Of String, String) = New Dictionary(Of String, String)

Sub Main()
    Words.Add("Zero", "0")
    Words.Add("One", "1")
    Words.Add("Two", "2")
    Words.Add("Three", "3")
    Words.Add("Four", "4")
    Words.Add("Five", "5")
    Words.Add("Six", "6")
    Words.Add("Seven", "7")
    Words.Add("Eight", "8")
    Words.Add("Nine", "9")

    Console.WriteLine("Enter a number to conver to words")
    Dim s As String = Console.ReadLine().ToString

    Console.WriteLine(ConvertNumbersToWords(s))

    Console.ReadKey()

End Sub

Private Function ConvertNumbersToWords(number As String)
    Dim ret As New StringBuilder

    For i As Integer = 0 To number.Length - 1
        ret.Append((From w In Words Where w.Value.Equals(number.ElementAt(i)) Select w.Key).First).Append(" ")
    Next

    Return ret.ToString.Trim
End Function

End Module