split string, VB.net? - vb.net

I have a file txt file that holds 3 values each seperated by a space how can i assign each value to its own variable and use that for other things?
as example the numbers might be displayed in the text file as:
-1100.02 -1958.19 0.0

Translating Marco’s C# code to VB:
Dim s As String = File.ReadAllText(filename)
Dim nums As String() = s.Split(" "c)
To get numbers, you need to parse the strings separately. You can use Linq to do this:
Dim numbers As Double() = From num In nums Select Double.Parse(num)

In C#:
string s = File.ReadAllText(filename);
string[] nums = s.Split(' ');
So you can access nums[index] where index should be between 0 and 2.
Note that you MUST check if everything went ok...
If you need you can also try:
foreach (string num in nums)
{
double d = double.Parse(num);
// Here you can do what you want with d
}

Try this:
Dim line as String = "-1100.02 -1958.19 0.0"
Dim values() as Double = Array.ConvertAll(line.Split(New Char() { " "c }, StringSplitOptions.RemoveEmotyEntries), AddressOf Convert.ToDouble)
This will result in values being filled with numbers from the input string (assuming a set of valid numbers on each line).

dim strSplitted() as string = Line.split(" "c)
' strSplitted(0), strSplitted(1) and strSplitted(2) will hold the values.
Line is the line in the file ofcourse :-)
update: code updated according to comments.

Related

How can I randomly select one of three strings?

I have to create a password and I believe that I can do it, however I am stumped at the very beginning. I have 3 strings of characters, I would like to randomly select one of these three strings. Does anybody know how to do it?
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
So I want to randomly select one of these three strings
I suggest you to use ListOf string instead for this. you can code like the following;
Dim listofStrings As New List(Of String) ' Declaration of list of strings
listofStrings.Add("qwertyuiopasdfghjklzxcvbnm") 'assign values to the list
listofStrings.Add("MNBVCXZLKJHGFDSAPOIUYTREWQ")
listofStrings.Add("1234567890")
Dim rnd As New Random
Dim randomString As String = listofStrings.Item(rnd.Next(0, 3))'select random string from the list
it will generate random numbers between 0 and 2 hence it will help you to select random string from the list of strings based on index referenced by the random number
The below code will help you generate a random number and then pick up the string at that position in the array
string[] arr= {"qwertyuiopasdfghjklzxcvbnm","MNBVCXZLKJHGFDSAPOIUYTREWQ","1234567890"};
Random rnd = new Random();
int cnt = rnd.Next(2);
string r = arr[cnt];

how to get value by split in vb.net 2005

i have a database in one field like below 222-225. I try to make split to read that value for my function. Just simple function a=225 b=222 then total=(a-b)+1. here my code
Dgv.CellClick
'Dim x As Boolean
Dim a As Double
Dim total As Double
a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value)
Split(a, "-")
total = (a) - (a)
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
My problem is this doesn't work. I can't get the value that I split. Any idea how to solve this problem?
note: I use VB.NET 2005
If you want total=(a-b)+1 .. That should be
dim b = a.Split("-")
total = val(b(1)) - val(b(2)) + 1
may be this can help. try this...
Dim a As String
a = ""
Dim x As String
Dim total As Double
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString
Dim ary() As String
x = a
ary = x.Split("-")
total = CInt(ary(1)) - CInt(ary(0))
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
Like others have said, Split() returns a String array, like this:
Dim SplitValue() As String = Split(a, "-")
total = (CType(SplitValue(1), Double) - CType(SplitValue(0), Double)) + 1
If I read your question correctly, the value you're looking for is 222-225, and that value is located in the specified cell of Dgv (which I'm guessing is a DataGridView). If my understanding is correct, there are a couple of things going on.
First, I'm not sure why you're trying to convert that value to a double with the following line of code:
a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value)
The Item property of a DataGridView holds a DataGridViewCell, and the Value property of the DataGridViewCell returns an Object. Trying to convert 222-225 to a double will, I believe, fail (though since this is VB.NET, it's possible it won't depending on the options you set - I'm not as familiar with VB.NET as I am with C#).
Even if it does successfully work (I'm not sure what the output would be), Split expects a string. I would change that line of code to the following:
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString()
Now you have a string that you can use Split on. The Split you have in your posted code appears to be the Visual Basic (pre-.NET) Split method Split Function (Visual Basic). As others have mentioned, Split returns an array of strings based on the delimiter. In your code, you don't assign the result of Split to anything, so you have no way to get the values.
I would recommend using the .NET version of Split (String.Split Method) - there are several ways you can call String.Split, but for purposes of your code I'd use it like this:
Dim splits As String() = a.Split(New Char() { "-" })
Where a is the string value from the selected DataGridViewCell above. This will give you a 2-element array:
splits(0) = "222"
splits(1) = "225"
The final part is your formula. Since you have strings, you'll need to convert them to a numeric data type:
total = (CDbl(splits(1)) - CDbl(splits(0))) + 1
Which becomes (225 - 222) + 1 = 4.
Putting it altogether it would look something like this:
Dim a As String
Dim total As Double
Dim splits() As String
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString()
splits = a.Split(New Char() { "-" })
total = (CDbl(splits(1)) - CDbl(splits(0))) + 1
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
Split returns an array. something like this. VB.Net is not my primary language but this should help.
dim arr = a.Split(New Char (){"-"})
total = ctype(arr(0), double) - ctype(arr(1),double)
Try this:
Dim aux() As String = a.Split("-"c)
total = CDbl(aux(0)) - CDbl(aux(1)) + 1
Dim a As string
Dim x As String
Dim total As Double
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value
Dim ary() As String
x = a
ary() = x.Split("-")
total = CInt(ary(1)) - CInt(ary(0))
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total

String Insert at a certain line

I am using Visual Basic.net.
If I have a string that has many lines in it, is it possible to insert a string at a certain line? I see that there is an insert function for strings. Is there a function to insert a string at a certain line of another string?
Is there a function to insert a string at a certain line of another
string?
No, because a string is not a list/array of lines. You have to split it by Environment.NewLine to get an array, ToList to get a List(Of String) which has an Insert method. Then you can use String.Join to put it together after you have inserted it:
Dim lines = MultiLineText.Split({Environment.NewLine}, StringSplitOptions.None).ToList()
lines.Insert(2, "test") ' will throw an ArgumentOutOfRangeException if there are less than 2 lines '
Dim result = String.Join(Environment.NewLine, lines)
There is no string methods that handles a string as a collections of lines. You can use the Insert method, but you have to find out where in the string to put the line yourself.
Example:
' Where to insert
Dim line As Integer = 4
' What to insert
Dim content As String = "asdf"
' Locate the start of the line
Dim pos As Integer = 0
Dim breakLen As Integer = Environment.Newline.Length
For i As Integer = 0 to line
pos = text.IndexOf(Environment.Newline, pos + breakLen)
Next
' Insert the line
text = text.Insert(pos, content + Environment.Newline)
Strings have no idea what a "line" is. A string is only a sequence of characters. What you can do is to convert your string into a list of individual lines (for example as List<string>) and then insert into that list.
List<string> listOfLines = new List<string>();
listOfLines.AddRange(sourceString.Split(new String[] { Environment.NewLine }, StringSplitOptions.None));
listOfLines.Insert(13, "I'm new here");
string result = String.Join(Environment.NewLine, listOfLines);
This is C# code, but I'm pretty sure you can easily convert this to VB.NET.

Flip letters of a string - Visual Basic

Simple coding assignment: Take text from a textbox and flip it so it's backwords:
i.e. Hello My Name Is David would be "divad si eman ym olleh" ( The program doesn't have to match case, just the letters)
This is something I found, do you have any other methods?
Dim str As String = Textbox1.Text
Dim arr As New List(Of Char)
arr.AddRange(str.ToCharArray)
arr.Reverse()
For Each l As Char In arr
lblOne.Text &= l
Next
You can do it in one line with using the StrReverse function (in Microsoft.VisualBasic).
Dim myText As String = "My Name is Dave"
Dim revText As String = StrReverse(myText)
Quick one liner.
lblOne.Text = String.Join("", "divad si eman ym olleh".Reverse())
Microsoft.VisualBasic
Dim myText As String = My Name is abc
Dim revText As String = StrReverse(myText)
Output: "cba si eman ym"
You can use String.Join instead of looping through each character and concatenating:
lblOne.Text = String.Join("", arr)
create a function that accepts string an returns a reversed string.
Function Reverse(ByVal value As String) As String
Dim arr() As Char = value.ToCharArray()
Array.Reverse(arr)
Return New String(arr)
End Function
and try using it like this,
lblOne.Text = Reverse(Textbox1.Text)
Here is a similar way but with fewer number of lines.
Dim Original_Text As String = "Hello My Name is Ahmad"
Dim Reversed_Text As String = ""
For i = Original_Text.Length To 1 Step -1
Reversed_Text &= Original_Text.Substring(i, 1)
Next
The simplest method to reverse a string is :
Dim s As String = "1234ab cdefgh"
MessageBox.Show(s.AsEnumerable.Reverse.ToArray)
First Create a textbox, it will be TextBox1
then create a button and name it Reverse
then Create a label, it will be Label1
Now double click on Reverse Button (Go to Button Click Event)
and type following code.
and run software And type your string in textbox and click on reverse button.
Dim MainText As String = TextBox1.Text
Dim revText As String = StrReverse(MainText)
Label1.Text = revText

compare a string and trim in vb.net

I have this string that shall come in from another file. The string has maximum length of 102 digits. I need to compare the string with numbers in a pair and delete those from that string.
e.g - 6125223659587412563265... till 102
numbers that compare with this string-
first set - 61
new string = 25223659587412563265
second set - 36
new string = 252259587412563265
and so on. the set of numbers shall go to maximum of 51 pairs = 102, which shall give an end result of string = ""
How can i achieve this in a loop?
this is not answer, this is editing the question. i dont know why but the edit button just vaniashed so i have to edit question here.
No duplicates will ever be in this string. and in the end when compares are done, i want to see what numbers are left in pairs.
Dim input As String = "6125223659587412563265"
Dim targets As String() = {"61", "36"}
For Each target As String In targets
input = input.Replace(target, "")
Next
Debug.Assert(input = "252259587412563265")
Here is a simple solution. You will need to add your pairs to the List(Of String) and also initialize input to the string you want to alter.
Dim pairs As New List(Of String)()
Dim input As String = String.Empty
For Each pair As String In pairs
input = input.Replace(pair, String.Empty)
Next