Visual Basic removing remaing string after delimiter - vb.net

I'm trying to remove the last part of the string to make it more presentable. The string looks like this
Stringname.number.RemainingStringTobeRemoved
Is there a way to remove the last part without using string.Substring(0,string.Length-10)?
I want it to be dynamic, the string I'll be removing is not a constant number.
My initial idea was to use delimiter to identify the starting point of the part I want to remove.

My initial idea was using delimiter to identify the starting point of the part I want to remove.
That's a good idea if your string is always the same format and the substring you want to remove does not contain that delimiter. Take a look at LastIndexOf.
Spoiler:
Dim s = "Stringname.number.RemainingStringTobeRemoved"
Dim r = s.Substring(0, s.LastIndexOf("."))

You can use Split to achieve this
String s = "Stringname.number.RemainingStringTobeRemoved"
Dim words As String() = s.Split(New Char() {"."c})
String RequiredString = words(0) & words(1)
The RequiredString is what you need

Using a delimiter is one way. You can use the Split method to split the string into parts at the ..
Dim FullString As String = "Stringname.number.RemainingStringTobeRemoved"
Dim StringParts() As String = Strings.Split(FullString, ".", 3)
Return StringParts(0) & StringParts(1)
The Split method returns an array of String that contains the parts. The array will contain the following items
Stringname
number
RemainingStringTobeRemoved
The delimiters are omitted.

Related

VB.net get specific characters from listbox

I want to get specific characters from listbox, but I don't know how to do it properly. I already used search (tried because I don't know how properly to name) but get nothing.
So i have this line in my listbox:
1,2014-01-01,Text,Text,XYZ123,Text,Text
How do i need to get only XYZ123? Its always same format, 3 letters and 3 numbers.
Thank you.
I would use a Regular Expression
The Regex of XYZ123 = \w{3}\d{3}
First solution:
Based on a small console application:
Dim i As String = "1,2014-01-01,Text,Text,**XYZ123**,Text,Text"
For Each Str As String In i.Split(",")
Dim match As Match = Regex.Match(Str, "\w{3}\d{3}")
If match.Success Then
Console.WriteLine(Str)
End If
Next
Console.ReadLine()
Second (better) solution:
Based on the comment of Chinz (all credits belong to him)
Dim i As String = "1,2014-01-01,Text,Text,**XYZ123**,Text,Text"
Console.WriteLine(Regex.Match(i, "\w{3}\d{3}").Value)
Console.ReadLine()
if all the strings have the same overall format you could split on "**" and get the [1] from the plitted

Isolate a a substring within quotes from an entire line

To start here is an example of a line I am trying to manipulate:
trait slot QName(PrivateNamespace("*", "com.company.assembleegameclient.ui:StatusBar"), "_-0IA") type QName(PackageNamespace(""), "Boolean") value False() end
I wrote a code that will go through and read through each line and stop at the appropriate line. What I am trying to achieve now is to read through the characters and save just the
_-0IA
to a new string. I tried using Trim(), Replace(), and indexof so far but I am having a ton of difficulties because of the quotation marks. Has anyone deal with this issue before?
Assuming your source string will always follow a strict format with only some data changes, something like this might work:
'Split the string by "," and extract the 3rd element. Trim the space and _
quotation mark from the front and extract the first 5 characters.
Dim targetstr As String = sourcestr.Split(","c)(2).TrimStart(" """.ToCharArray).Substring(0, 5)
If the length of the target string is variable it can be done like this:
Dim temp As String = teststr.Split(","c)(2).TrimStart(" """.ToCharArray)
'Use the index of the next quotation mark instead of a fixed length
Dim targetstr As String = temp.Substring(0, temp.IndexOf(""""c))

Extracting characters from an input string vb.net

Hey guys I'm stuck with this question. Please help.
I want to write a program that can extract alphabetical characters and special characters from an input string. An alphabetical character is any character from "a" to "z"(capital letters and numbers not included") a special character is any other character that is not alphanumerical.
Example:
string = hello//this-is-my-string#capetown
alphanumerical characters = hellothisismystringcapetown
special characters = //---#
Now my question is this:
How do I loop through all the characters?
(the for loop I'm using reads like this for x = 0 to strname.length)...is this correct?
How do I extract characters to a string?
How do I determine special characters?
any input is greatly appreciated.
Thank you very much for your time.
You could loop through each character as follows:
For Each _char As Char In strname
'Code here
Next
or
For x as integer = 0 to strname.length - 1
'Code here
Next
or you can use Regex to replace the values you do not need in your string (I think this may be faster but I am no expert) Take a look at: http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx
Edit
The replacement code will look something as follows although I am not so sure what the regular expression (variable called pattern currently only replacing digits) would be:
Dim pattern As String = "(\d+)?" 'You need to update the regular expression here
Dim input As String = "123//hello//this-is-my-string#capetown"
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, "")
Since you need to keep the values, you'll want to loop through your string. Keeping a list of characters as a result will come in handy since you can build a fresh string later. Then take advantage of a simple Regex test to determine where to place things. The psuedo code looks something like this.
Dim alphaChars As New List(Of String)
Dim specialChars As New List(Of String)
For Each _char As Char in testString
If Regex.IsMatch(_char, "[a-z]")) Then
alphaChars.Add(_char)
Else
specialChars.Add(_char)
End If
Next
Then If you need to dump your results into a full string, you can simply use
String.Join(String.Empty, alphaChars.ToArray())
Note that this code makes the assumption that ANYTHING else than a-z is considered a special character, so if needs be you can do a second regular expression in your else clause to test for you special characters in a similar manner. It really depends on how much control you have over the input.

Can't split string with space character using Split(" "c) vb.net

I'm trying to split a Yahoo historical stock price csv file, downloaded into a string, by what looks like a space character. I want a new row for each split. The split function works for other characters I see in the string. I suspect the characters may be a non breaking space character but I've been unable to split on them.
This is the test csv file that is downloaded into the string:
http://ichart.finance.yahoo.com/table.csv?s=AAPL&c=2011
I'm trying to split the string like this:
Dim rows As String() = data.Split(" "c)
There is a real space character in the header part of the string that this breaks on, but not the white space characters in the stock data I want to split. If this is a non breaking space, how do I split on it? How can I tell what this white space character is?
A Sample of the string looks like this:
"Date,Open,High,Low,Close,Volume,Adj Close 2011-12-27,69.24,72.18,69.01,71.55,1491000,71.55 2011-12-23,67.49,69.25,67.25,69.08,880300,69.08"
I'm trying to split at the space before the stock dates, "2011-12-23", for example.
This is my function:
Public Shared Function DownloadData(ByVal ticker As String, ByVal yearToStartFrom As Integer) As List(Of HistoricalStock)
Dim retval As New List(Of HistoricalStock)()
Using web As New WebClient()
Dim data As String = web.DownloadString(String.Format("http://ichart.finance.yahoo.com/table.csv?s={0}&c={1}", ticker, yearToStartFrom))
Dim rows As String() = data.Split(" "c)
Return retval
End Using
End Function
Those "spaces" that you talk about aren't really spaces, they are line returns. You probably opened it with NotePad, where it's displayed as a space, because it tries to open it with the wrong encoding, I suppose.
Open it with WordPad or Excel and you'll see the line returns. You will need to split on vbLf for it to work:
Dim rows As String() = data.Split(vbLf)
Those are not spaces. They are line feeds. This will correct it.
Dim rows As String() = data.Split(vbLf)

VB.NET split string with quotation marks in it

Trying to split a line wherever "," appears (with the quotation marks). The problem is VB.NET uses " to start/end strings, so I tried using .Split(""",""") but that then splits it by " not ",".
Try something like this:
Dim TestToSplit As String = "Foo"",""Bar"
Dim Splitted() As String = TestToSplit.Split(New String() {""","""}, StringSplitOptions.None)
I just tested it and got an array with Foo And Bar. I hope this helps.
The Split function (the way you are using it) expects a Char. If you want to split on multiple characters you need to use a string array. (Seems to me another overload of a single string value would have been handy.)
This function splits a line of text and returns an array based on the delimiter you have specified. (Of course, you could make this more general purpose by passing in the separator array.)
Private Function SplitLine(ByVal lineOfText As String) As String()
Dim separator() As String = {""","""}
Dim result() As String
result = lineOfText.Split(separator, StringSplitOptions.None)
Return result
End Function
Another alternative I often find useful is this:
Regex.Split(textToSplit, """,""")
Lets you split on more complex criteria than an array of alternative separators.
To escape the "-character in VB.NET, use two: ""