John M John M - 1 month ago 20
Vb.net Question

String Manipulation in Vb.net

I have the following scenarios:


  1. str = "Upper Left 1 Upper Left 2"



I want the result to be newStr = "Upper Left 1 and 2"


  1. str = "Upper Left 8 Upper Left 8"



I want the result to be newStr = "Upper Left 8"


  1. str = "Upper Left 5 Upper Right 9"



I want the result to be newStr = "Upper Left 5 Upper Right 9"

I tried replace, distinct and split but none seem to do what I want.

Any ideas?

Answer

As always, there are many ways to do this. What is the best one depends on how many cases you have. I'd do it like this:

Dim partList as List(Of String) = str.Split(" ").toList()
if(partList.item(1) = partList.item(4) AndAlso partList.item(2) = partList.item(5)) Then
    newStr = partList.item(0) + partList.item(1) + partList.item(2)
elseif(partList.item(1) = partList.item(4)) Then
    newStr = partList.item(0) + partList.item(1) + partList.item(2) + " and "+ partList.item(5)
else
    newStr = str
End If