How to get value from expression in vb.net - vb.net

I have the following string expression:
str="1+2+3+4"
Now from this string I want the value of number (10). How can I get this value from this expression?

For that to work, you'd have to parse all the numbers, something like this
Dim str As String= "1+2+3+4"
Dim numbers() As String = str.Split('+')
Dim result As Integer = 0
For Each number As String In numbers
result += Integer.Parse(number)
Next

Here is an alternative solution that uses Linq. This solution excludes nothing it can not parse...
YOURSTRING.Split("+").ToList.Where(Function(sr) Not String.IsNullOrEmpty(sr) AndAlso Integer.TryParse(sr, New Integer)).Sum(Function(s As String) Integer.Parse(s))
Example Output
1+2+3+4 = 10
1+2+3+4++12+1 = 23 (Notice the typo (4++12), it still works even it there's a mistake)

Related

Get the character after a combination of characters in a string

I have a string ABC(N9KGRTLMN9(0J)M3.
I want to return the character after GRTLM which is N. Thanks.
Look at the System.Text.RegularExpressions namespace, and create a RegEx object with this expression:
GRTLM(.)
Then you will be able to check the Matches for the expression to find your character. Depending on what you know about that string, you may be able to narrow things even further. For example:
GRTLM([A-Za-z])
or
GRTLM([A-Z])
If you don't want to use regular expressions (for any reason), here's an alternative:
Private Function ReturnCharAfter(Source As String, after As String) As Char
Dim i As Integer = Source.IndexOf(after)
If i < 0 Then Return Nothing
Return Source(i + after.Length)
End Function
usage:
Dim N As Char = ReturnCharAfter("ABC(N9KGRTLMN9(0J)M3.", "GRTLM")
You could use String.Split() to get the N
Dim input = "ABC(N9KGRTLMN9(0J)M3"
Dim s = "GRTLM"
Dim n = input.Split({s}, StringSplitOptions.RemoveEmptyEntries)(1)(0)
It splits the string into substrings using GRTLM as a delimiter, then returns the first character of the second array item.
Or to get the index of N
Dim i = input.Split({s}, StringSplitOptions.RemoveEmptyEntries)(0).Length + s.Length
It splits the string and returns the length of the first array item plus the length of the delimiter string.
But perhaps the simplest way to do it is using String.IndexOf()
Dim n = input(input.IndexOf(s) + s.Length)
Dim i = input.IndexOf(s) + s.Length

I wrote a code which reverses a string (and it does), but I don't think it's the clean/right way to do it

I wanted to get familiar with the built-in functions of VB, specifically, the len() function.
However, I think this may not be the right way to concatenate a string with a char.
Also, it may interest you that the error list says,
"Warning 1 Variable 'reverse' is used before it has been assigned a
value. A null reference exception could result at runtime."
I executed the program but it ran fine. Here's the code:
Sub Main()
Dim a As String
Console.WriteLine("Enter the value of the string you want to reverse: ")
a = Console.ReadLine()
Dim reverse As String
Dim temp As Char
Dim str As Integer
str = Len(a)
For x = str To 1 Step -1
temp = Mid(a, x)
reverse = reverse + temp
Next x
Console.WriteLine(reverse)
Console.ReadKey()
End Sub
I'm still learning this language and so far it's been really fun to make small programs and stuff.
Dim TestString As String = "ABCDEFG"
Dim revString As String = StrReverse(TestString)
ref: https://msdn.microsoft.com/en-us/library/e462ax87(v=vs.90).aspx
You are getting the warning
"Warning 1 Variable 'reverse' is used before it has been assigned a
value. A null reference exception could result at runtime."
Because String variable reverse is not yet initialized. Compiler will consider the scenario that For is not executing in such situation the reverse can be null. you can get out of the warning by assigning an empty value to the string: ie.,
Dim reverse As String=String.Empty
You can do the functionality in the following ways too:
Dim inputStr As String = String.Empty
Console.WriteLine("Enter the value of the string you want to reverse: ")
inputStr = Console.ReadLine()
Dim reverse As String = String.Join("", inputStr.AsEnumerable().Reverse)
Console.WriteLine(reverse)
Console.ReadKey()
OR
Dim reverse As String = String.Join("", inputStr.ToCharArray().Reverse)

Remove the character alone from the string

My code retrieves the data from various resources .
And output will be like below
UNY4/4/2010
hds04/5/2010
saths04/22/2013
But I want the output like this
4/4/2010
4/5/2010
04/22/2013
Is there any way to do this ?
You need to use a regular expression that finds all uppercase and lowercase characters and replaces them with a blank, like this:
Dim rgx As New Regex("[a-zA-Z]")
str = rgx.Replace(str, String.Empty)
An alternate solution is to look for the first numeric digit, then discard all text before that.
Function GetDate(data As String) As Date
Dim indexFirstNum As Integer = data.IndexOfAny("0123456789".ToCharArray())
Dim datePortion As String = data.Substring(indexFirstNum)
Return Date.Parse(datePortion)
End Function

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

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