将整数添加到vb.net中的另一个整数?

时间:2018-09-12 15:28:07

标签: vb.net

如何在vb.net中向另一个整数添加一个整数?

这是我需要做的:

给出整数:2187-> 转换后的整数:2018

我需要在第一个和第二个数字之间添加一个0,并删除最后一个数字。这将给我一年。

这是我拥有的代码:

Protected Function GetYear(ByVal term As Integer) As Integer

    Dim termYear As String = Convert.ToString(term)

    termYear.Substring(0, 2)
    termYear.Insert(1, "0")

    Dim convertedYear As Integer
    Int32.TryParse(termYear.ToString, convertedYear)

    convertedYear = convertedYear / 10

    Return convertedYear

End Function

3 个答案:

答案 0 :(得分:2)

通常,字符串是不可变的。因此,您必须从添加的子字符串中创建一个新的字符串。检查此可能的解决方案。

Function GetYear(ByVal term As Integer) As Integer

    Dim termYear As String = Convert.ToString(term, Globalization.CultureInfo.InvariantCulture)

    Dim result As String = termYear.Substring(0, 1) + "0" + termYear.Substring(1, 2)

    Return Int32.Parse(result)

End Function

答案 1 :(得分:1)

字符串是不可变的,当您使用其中一种方法进行任何更改时,都需要获取返回的字符串。

termYear = termYear.Insert(1, "0")

答案 2 :(得分:0)

这个问题值得一个基于数学的解决方案。下面的代码指定相对于数字右侧的零插入点,而不是问题语句中所述的左侧。因此,对于4位数字,插入点是3对2。它还允许您更改插入点。

Private Function GetYear(ByVal term As Integer, Optional zeroDigitPosition As Integer = 3) As Integer
    If zeroDigitPosition > 0 Then
        Dim divisor As Integer = 1
        For i As Integer = 1 To zeroDigitPosition - 1
            divisor *= 10
        Next
        Dim ret As Integer = term \ 10 ' drop one's place digit, remaining digits shift to right
        Dim rightShiftedDigits As Integer = ret Mod divisor
        Dim remainder As Integer = Math.DivRem(ret, divisor, rightShiftedDigits)
        ' shift the remainder to the left by divisor * 10 
        ' (remember first right shift invplved \ 10) and add
        ' rightShiftedDigits to yield result
        Return (remainder * divisor * 10) + rightShiftedDigits
    Else
        Throw New ArgumentOutOfRangeException("zeroDigitPosition must be greater then zero")
    End If
End Function