如何将字符串添加到列表(索引)中取决于字符串在 vb.net 中的条件



如果字符串中没有";",我想在字符串的索引中插入字符串。 这是示例字符串:-

[1234] 1 ABC 123;
[5678] 2 DEF 456; 
[9874] 1 GHI 987
[1234] 1 ABC 123;
[5678] 2 DEF 456; 
[9874] 1 GHI 987

我想在字符串包含 ";" 时制作它,它仍然在索引 (0( 中,然后当字符串没有 ";" 时,例如[9874] 1 GHI 987,它将继续到下一个索引(1(.. 循环继续。

所以输出应该是这样的:

[1234] 1 ABC 123; [5678] 2 DEF 456;  [9874] 1 GHI 987
[1234] 1 ABC 123; [5678] 2 DEF 456; [9874] 1 GHI 987

我尝试的是

Dim ulist As List(Of String) = New List(Of String)
Dim olist As List(Of String) = New List(Of String)
Dim tempp As String = ""
For i As Integer = 0 To ulist.Count - 1 Step 1
If i = 0 Then
tempp = ulist(i).ToString
ElseIf i = ulist.Count - 1 Then 
If ulist(i).ToString.Contains(";") Then
olist.Add(tempp)
tempp = ulist(i).ToString
olist.Add(tempp)
Else
tempp = tempp & " " & ulist(i).ToString
olist.Add(tempp)
End If
Else 
If ulist(i).ToString.Contains(";") Then
olist.Add(tempp)
tempp = ulist(i).ToString
Else
tempp = tempp & " " & ulist(i).ToString
End If
End If
Next

但是,使用上面的代码,输出显示:

[1234] 1 ABC 123; 
[5678] 2 DEF 456;  [9874] 1 GHI 987
[1234] 1 ABC 123; 
[5678] 2 DEF 456; [9874] 1 GHI 987
Dim oIndex As Integer = 0 'index for oList
Dim builder As New StringBuilder() 'used to build a line before inserting into olist
For uIndex = 0 To ulist.Count - 1
If ulist(uIndex).Contains(";") Then
'If ; exists, keep building string
builder.Append(ulist(uIndex)).Append(" ") 
Else 
'If ; does not exist, add last entry to string            
builder.Append(ulist(uIndex))  
'add string to olist
olist.Add(builder.ToString)
'clear string
builder.Clear()
'increment olist index (start new line)
oIndex = oIndex + 1
End If
Next

相关内容

最新更新