用条件替换文本(VB.Net)

时间:2018-05-24 10:21:12

标签: vb.net

如何用VB.Net中的条件替换文本

ItemNumber = "2.4.1.2.1" become PartNumber = "02-04-01-02" 
ItemNumber = "22.4.1.20.10" become PartNumber "22-04-01-20"
ItemNumber = "1.1" become PartNumber "01"

谢谢@Andrew。我试着修改你的代码。这是代码:

Dim ItemNumber As String = "22.4.1.20.100.5"
Dim PartNumbers As String() = ItemNumber.Split(New Char() {"."c})
Dim x As Integer = PartNumbers.Length - 1
Dim myRange = PartNumbers.Take(x).Select(Function(a) a.PadLeft(2, "0"c))
Dim PartNumber = String.Join("-", myRange)
Console.WriteLine(PartNumber)

2 个答案:

答案 0 :(得分:1)

另一种思考方式是你需要前四个部分,并且你希望这些部分用零填充:

Dim partNumber = String.Join("-", itemNumber.Split("."c).Take(4).Select(Function(a) a.PadLeft(2, "0"c)))

答案 1 :(得分:0)

您可以使用以下解决方案:

Dim ItemNumber As String = "22.4.1.20.10"
Dim ItemsNumber() As String = ItemNumber.Split("."c)
ReDim Preserve ItemsNumber(ItemsNumber.Length - 2)

For numberIndex As Integer = 0 To ItemsNumber.Length - 1
    ItemsNumber(numberIndex) = ItemsNumber(numberIndex).PadLeft(2, "0")
Next

Dim PartNumber As String = Strings.Join(ItemsNumber, "-")

'22.4.1.20.10   -->  22-04-01-20
'2.4.1.2.1      -->  02-04-01-02
'22.4.1.20.10.5 -->  22-04-01-20-10