拆分String并将内容存储到3个不同的变量中

时间:2017-08-16 18:19:39

标签: .net vb.net

我能够很好地分割字符串List,但我现在想在每个循环中相应地将内容放在3个不同的变量中。

这是我使用的列表变量,但我刚刚在一个字符串下方发布以显示结构。

myString = "Toyota, Truck, 1996"

Dim var1, var2, var3 as String

Dim myString As String() = item1.Split(New Char() {","c})


Dim myValue As String

For Each myValue In myString

    Console.WriteLine(myValue)

Next

==

Result should be :

var1 = Toyota
var2 = Truck
var3 = 1996

2 个答案:

答案 0 :(得分:1)

' List holding multiple strings
Dim myListVariable As New List(Of String) From {
    "Toyota, Truck, 1996",
    "Ford, Car, 1998",
    "Harley, Motorcycle, 1990"}
' Loop over each string
For Each myString In myListVariable
    ' Split each string into another List
    Dim myList = myString.Split({",", " "}, StringSplitOptions.RemoveEmptyEntries).ToList()
    Console.WriteLine()
    ' assign to individual variables ...
    Dim var1 = myList(0)
    Dim var2 = myList(1)
    Dim var3 = myList(2)
    ' ... or iterate over items and print
    For Each myValue In myList
        Console.WriteLine(myValue)
    Next
Next

输出

  


丰田   
卡车   1996年
  
  
福特   
汽车   1998年
  
  
哈雷   
摩托车   
1990

答案 1 :(得分:0)

非常简单。试试这个:

Dim myString As String() = item1.Split(New Char() {","c})
Dim Vehicle As String = myString(0)  
Dim Type As String = myString(1) 
Dim Year As String = myString(2)

编辑1:正如您所评论的那样,您使用的是List(Of String)变量,我们假设ListOfDetails是问题中的变量。然后

For Each detail as String In ListOfDetails
   Dim myString As String() = detail.Split(New Char() {","c})

   'Store values in variable like this if you want to
   Dim Vehicle As String = myString(0)
   Dim Type As String = myString(1)
   Dim Year As String = myString(2)
   'And print them using
   Console.WriteLine(Vehicle)
   Console.WriteLine(Type)
   Console.WriteLine(Year)

   'Else you can print them directly using this
   For Each myValue In myString
     Console.WriteLine(myValue)
   Next
Next