简体   繁体   English

仅将混合字符串中的数字相乘[VB.Net]

[英]Multiply only numbers in a mixed string [VB.Net]

Let's say I have a string "N4NSD3MKF34MKMKFM53" and i want to multiply the string * 2 to get 假设我有一个字符串“N4NSD3MKF34MKMKFM53”,我想将字符串* 2乘以得到

N8NSD6MKF68MKMKFM106 How would I go about doing this? N8NSD6MKF68MKMKFM106我该怎么做呢?

Ok, I might as well give you the Regex solution as long as I'm here. 好吧,只要我在这里,我不妨给你正则表达式解决方案。 But I caution you not to use it unless you understand what it's doing. 但我提醒你不要使用它,除非你明白它在做什么。 It's never a good idea to just copy and paste code that you don't fully understand. 复制和粘贴您不完全理解的代码绝不是一个好主意。

Dim input As String = "N4NSD3MKF34MKMKFM53"
Dim output As String = Regex.Replace(
                                 input, 
                                 "\d+", 
                                 Function(x) (Integer.Parse(x.Value) * 2).ToString())

You can try the following code: 您可以尝试以下代码:

Public Class Program
Public Shared Sub Main(args As String())

        Const  expression As String = "N4NSD3MKF34MKMKFM53"

        Dim  result = MultiplyExpression.Calculate(expression)
        Console.WriteLine(result)
    End Sub
End Class

Class MultiplyExpression
    Public Shared Function Calculate(expression As String) As String
        Dim result = String.Empty
        For  Each c In expression
            Dim num As Integer
            If Int32.TryParse(c.ToString(), num) Then
                result += (num * 2).ToString()
            Else
                result += c
            End If
        Next

        Return result
    End Function
End Class

Output: N8NSD6MKF68MKMKFM106 输出:N8NSD6MKF68MKMKFM106

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM