retrieve unique values from string of numbers - vb.net

i have this string
Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
and want to retrieve a string
newstr = 12,32,15,16,14
i tried this much
Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
Dim word As String
Dim uc As String() = test.Split(New Char() {","c})
For Each word In uc
' What can i do here?????????
Next
only unique numbers how can i do that in vb asp.net
right answer
Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
Dim word As String
Dim uc As String() = test.Split(New Char() {","c}).Distinct.ToArray
Dim sb2 As String = "-1"
For Each word In uc
sb2 = sb2 + "," + word
Next
MsgBox(sb2.ToString)

Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
Dim uniqueList As String() = test.Split(New Char() {","c}).Distinct().ToArray()

Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
'Split into an array
Dim testArray As String() = test.Split(",")
'remove duplicates
Dim uniqueTestArray As String() = testArray.Distinct().ToArray())
'Concatenate back to string
Dim uniqueString As String = String.Join(",", uniqueTestArray)
Or all in one line:
Dim uniqueString As String = String.Join(",", test.Split(",").Distinct().ToArray())

Updated Sorry I forgot to add the new string together
Solution:
Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
Dim distinctArray = test.Split(",").Distinct()
Dim newStr As String = String.Join(",", distinctArray.ToArray())
Training References: Check out this website for a guide on LINQ which will make these types of programming challenges easier for you. LINQ Tutorial

You forgot to put parentheses for Distinctand ToArray. Because these are methods
Dim uc As String() = test.Split(New Char() {","c}).Distinct().ToArray()

Related

String Manipulation from "[1_5],[1_3],[1_5]" to "5,3,5"

I have the a string in below format
Dim str as String = "[1_5],[1_3],[1_5]"
The part before the _ can be variable is not a fix number
i need to convert it in to format
"5,3,5"
i have used the below code to obtain all the number that i need in the new string in the matches Item Groups
Dim pattern As String = "_(.*?)\]"
Dim matches As MatchCollection =
Regex.Matches(rowpanel.getRequestedArea_selectionArea(), pattern, RegexOptions.Singleline)
My question is how i can join all the Groups to obtain the final string format ?
A Regex solution could be
Dim x = matches.Select(Function(g) g.Groups(1).Value)
Dim final = String.Join(",", x)
A Split and Join one is
Dim blocks As String() = str.Split(",")
Dim result = New List(Of String)()
For Each s In blocks
result.Add(s.Split("_")(1).Trim("]"))
Next
Dim final = String.Join(",", result)
You can do something like this using RegEx and replace:
Dim str As String = "[1_5],[1_3],[1_5]"
Dim RegX As Regex = New Regex("\[\d{1}_")
Dim match As Match = RegX.Match(str)
If match.Success Then
str = Replace(str, match.Value, "")
str = Replace(str, "]", "")
End If
Alternative with simple and readable loop but multiple lines of code wrapped with a method
Public Function ExtractNumbers(text As String) As String
Dim current As New StringBuilder()
Dim write As Boolean = False
For Each character As Char In text
If character = "_"c Then
write = True
Continue For
End If
If character = "]"c Then
write = False
current.Append(",")
Continue For
End If
If write Then
current.Append(character)
Continue For
End If
Next
current.Length -= 1
Return current.ToString()
End Function
Usage
var extracted = ExtractNumbers("[1_5],[1_3],[1_5]")
Console.WriteLine(extracted)
' 5,3,5

Extracting Portion of Url using VB.net

I have this URL
https://www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607
I am trying to Extract 31.888433,73.263572 from the URL
and send 31.888433 to TextBox 1
and 73.263572 to TextBox 2
Can you give me an example how can i do this with regex or anything else
You can use string.split(). This method takes an array of chars which are the discriminants for the splitting. The better solution is to split by '/', take the string that starts with '#' and then split it by ','. You'll have an array with two string: first latitude, second longitude.
Should be immediate using LINQ
The explanation is in the code comments.
Dim strURL As String = "https://www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607"
'Find the index of the first occurance of the # character
Dim index As Integer = strURL.IndexOf("#")
'Get the string from that the next character to the end of the string
Dim firstSubstring As String = strURL.Substring(index + 1)
'Get a Char array of the separators
Dim separators As Char() = {CChar(",")}
'Split the string into an array based on the separator; the separator is not part of the array
Dim strArray As String() = firstSubstring.Split(separators)
'The first and second elements of the array is what you want
Dim strTextBox1 As String = strArray(0)
Dim strTextBox2 As String = strArray(1)
Debug.Print($"{strTextBox1} For TextBox1 and {strTextBox2} for TextBox2")
Finally Made a working Code Myself
Private _reg As Regex = New
Regex("#(-?[\d].[\d]),(-?[\d].[\d])", RegexOptions.IgnoreCase)
Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1.Click
Dim url As String = WebBrowser2.Url.AbsoluteUri.ToString()
' The input string.
Dim value As String = WebBrowser2.Url.ToString
Dim myString As String = WebBrowser2.Url.ToString
Dim regex1 = New Regex("#(-?\d+\.\d+)")
Dim regex2 = New Regex(",(-?\d+\.\d+)")
Dim match = regex1.Match(myString)
Dim match2 = regex2.Match(myString)
If match.Success Then
Dim match3 As String = match.Value.Replace("#", "")
Dim match4 As String = match2.Value.Replace(",", "")
Label1.Text = match3
Label2.Text = match4
End If
End Sub
Dim url As String = "www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607"
Dim temp As String = Regex.Match(url, "#.*,").Value.Replace("#", "")
Dim arrTemp As String() = temp.Split(New String() {","}, StringSplitOptions.None)
Label1.Text = arrTemp(0)
Label2.Text = arrTemp(1)

VB - Had a function working, doesn't anymore

EDIT: Ok, it's because I'm using 2.0 Framework. Any ideas how I can modify that area or alternatives? I have to, unfortunately, stick with 2.0
Dim dir2 As New DirectoryInfo("d:\input")
Dim sw2 As New StreamWriter("d:\input\reportCond.txt")
For Each fi2 As FileInfo In dir2.GetFiles("report.txt")
Dim sr2 As New StreamReader(fi2.FullName)
While Not sr2.EndOfStream
Dim sLine As String = sr2.ReadLine
Dim myPath As String = sLine
Dim fileName As String =System.IO.Path.GetFileNameWithoutExtension(myPath)
Dim letters As String = fileName.Where(Function(c) Char.IsLetter(c)).ToArray
Dim comp As String = sLine.Substring(28)
sw2.WriteLine(letters)
End While
Next
The Code above was working fine yesterday, today it doesn't and I can't figure out why. The only difference was yesterday I ran it on VS2013, today it doesn't work on VS2010.
I get an error on Function saying "expression expected"
And another one on sw2.WriteLine(letters) saying "Name 'letters' is not declared.
Here is how the linq Where part can be replaced to get the letters variable - which contains characters from the file name.
dim c as char
Dim letters As String
for each c in s
if char.IsLetter(c)
letters += c
end if
next
I would use the StringBuilder class to build the string:
Dim dir2 As New DirectoryInfo("d:\input")
Dim sw2 As New StreamWriter("d:\input\reportCond.txt")
For Each fi2 As FileInfo In dir2.GetFiles("report.txt")
Dim sr2 As New StreamReader(fi2.FullName)
While Not sr2.EndOfStream
Dim sLine As String = sr2.ReadLine
Dim myPath As String = sLine
Dim fileName As String =System.IO.Path.GetFileNameWithoutExtension(myPath)
' Build string
Dim sb As New System.Text.StringBuilder()
For Each c As Char In fileName
If Char.IsLetter(c) Then
sb.Append(c)
End If
Next
Dim comp As String = sLine.Substring(28)
' Here's the string you built
Dim letters As String = sb.ToString()
sw2.WriteLine(letters)
End While
Next
A .Net 2.0 framework alternative to the Where extension method could be:
Dim letters As String = Array.FindAll(fileName.ToCharArray(), AddressOf Char.IsLetter)
This will create a new array of chars whose elementes will be all chars of fileName.ToCharArray for wich Char.IsLetter is True

IndexOutOfRange exception with String.Split

Getting an error on this code which is part of a function to receive a message, it takes the querystring values and splits them or at least is supposed to right now it gives me an index out of range trying to assign the value to paramValue as string=params(1).ToString and I am not sure why?
Dim QueryString As String() = context.Split("&")
Dim QuerySet As String
Dim Params As String() = Nothing
For Each QuerySet In QueryString
Params = QuerySet.Split("=")
Dim ParamKey As String = Params(0).ToString.ToLower
Dim ParamValue As String = Params(1).ToString
Not an answer, but won't fit as a comment:
For Each QuerySet As String() In context.Split("&"c)
Dim Params As String() = QuerySet.Split("="c)
Next
Add some error checking to your code:
Dim QueryString As String() = context.Split("&"c)
Dim QuerySet As String
Dim Params As String() = Nothing
For Each QuerySet In QueryString
If QuerySet.Contains("=") Then 'procede
Params = QuerySet.Split("="c)
Dim ParamKey As String = Params(0).ToLower
Dim ParamValue As String = Params(1)
'use variables
End If
Next

Split a string in VB.NET

I am trying to split the following into two strings.
"SERVER1.DOMAIN.COM Running"
For this I use the code.
Dim Str As String = "SERVER1.DOMAIN.COM Running"
Dim strarr() As String
strarr = Str.Split(" ")
For Each s As String In strarr
MsgBox(s)
Next
This works fine, and I get two message boxes with "SERVER1.DOMAIN.COM" and "Running".
The issue that I am having is that some of my initial strings have more than one space.
"SERVER1.DOMAIN.COM Off"
There are about eight spaces in-between ".COM" and "Off".
How can I separate this string in the same way?
Try this
Dim array As String() = strtemp.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
Use this way:
Dim line As String = "SERVER1.DOMAIN.COM Running"
Dim separators() As String = {"Domain:", "Mode:"}
Dim result() As String
result = line.Split(separators, StringSplitOptions.RemoveEmptyEntries)
Here's a method using Regex class:
Dim str() = {"SERVER1.DOMAIN.COM Running", "mydomainabc.es not-running"}
For Each s In str
Dim regx = New Regex(" +")
Dim splitString = regx.Split(s)
Console.WriteLine("Part 1:{0} | Part 2:{1}", splitString(0), splitString(1))
Next
And the LINQ way to do it:
Dim str() = {"SERVER1.DOMAIN.COM Running", "mydomainabc.es not-running"}
For Each splitString In From s In str Let regx = New Regex(" +") Select regx.Split(s)
Console.WriteLine("Part 1:{0} | Part 2:{1}", splitString(0), splitString(1))
Next