开发者

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, e.g.

    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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜