简体   繁体   中英

How do I detect for a specific character in a string in VB.NET?

Okay, so in a program I'm working on in VB.NET I'm trying to make it so I can take in a list of strings (each on a different line). For each line I want to take in the line, and break it up into three parts. The first part goes from the beginning of the string to the first colon in the string, the second part goes from the first colon to the at symbol, and the last part goes from the at symbol to the end of the string.

For example, I'd take in a line of the series of lines: hello:world@yay

I'd want to break it into three separate strings of "hello", "world", and "yay".

How would I do such a thing in VB.NET?

You can accomplish this with a Split . For example purposes, I am re-splitting a string which I could have saved off, so I wouldn't have to Split it again. However, it's simpler to understand this way:

Dim s as String = "hello:world@yay" 'This can be a string from a loop.
Dim hello As String = s.Split(":")(0)  'Get everything before colon.
Dim world As String = s.Split(":")(1).Split("@")(0) 'Get everything after colon, and split the result again, grabbing everything before the amp.
Dim yay As String = s.Split(":")(1).Split("@")(1) 'Get everything after colon, and split the result again, grabbing everything after the amp.

If you're reading from a text file, eg

    Dim objReader As New StreamReader("c:\test.txt")
    Dim s As String = ""
    Dim hello As String
    Dim world As String
    Dim yay As String

    Do
        s = objReader.ReadLine()
        If Not s Is Nothing Then
           hello = s.Split(":")(0)
           world = s.Split(":")(1).Split("@")(0)
           yay = s.Split(":")(1).Split("@")(1)
        End If
    Loop Until s Is Nothing
    objReader.Close()

Use the split command

Start by splitting the string with the ":" and then split the second edit element with the "@"

Look at string.indexOf and take it from there

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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