Flip letters of a string - Visual Basic - vb.net

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

Related

How to convert a string to a vb expression which includes control name in it

.. eg: have a stri ng
strResult="controlName1.value * controlName2.value"
.. I need to change it to just controlName1.value * controlName2.value so that i can get the output as double value
Please reply
Thanks
If you're using Windows Forms, there is an indexer property that accepts the name of a sub-control as a string and returns the control if a match is found. See: Control.ControlCollection.Item Property (String).aspx
The straightforward alternative in all UI frameworks is to map Strings to Controls like such:
Function MapStringToControl(ctlName As String) As Control
Select Case ctlName
Case "controlName1"
Return controlName1
Case "controlName2"
Return controlName2
Case Else
Return Nothing
End Function
Of course note that there is no .Value property in Windows Forms--you need to do something like Integer.Parse(ctl.Text).
It depends what type of control it is. For example a textbox has a .Text property. A NumericUpDown control has a .Value property.
All you need to do is to convert the appropriate property to the appropriate type. So for TextBoxes:
Dim result as Double = CDbl(txtFoo.Text) * CDbl(txtBar.Text)
For a NumericUpDown:
Dim result as Double = CDbl(nudFoo.Value) * CDbl(numBar.Value)
Hi guys thanks for your updates.. I wrote my own function by using your concepts and some other code snippets .I am posting the result
Function generate(ByVal alg As String, ByVal intRow As Integer) As String
Dim algSplit As String() = alg.Split(" "c)
For index As Int32 = 0 To algSplit.Length - 1
'algSplit(index) = algSplit(index).Replace("#"c, "Number")
If algSplit(index).Contains("[") Then
Dim i As Integer = algSplit(index).IndexOf("[")
Dim f As String = algSplit(index).Substring(i + 1, algSplit(index).IndexOf("]", i + 1) - i - 1)
Dim grdCell As Infragistics.Win.UltraWinGrid.UltraGridCell = dgExcelEstimate.Rows(intRow).Cells(f)
Dim dblVal As Double = grdCell.Value
algSplit(index) = dblVal
End If
Next
Dim result As String = String.Join("", algSplit)
'Dim dblRes As Double = Convert.ToDouble(result)
Return result
End Function
Thanks again every one.. expecting same in future

how to get the fix substring from dynamic string content?

I am developing VB.NET windows app. in VS 2010.
I want to get the substring
$CostCenterId|4^10
from the below string .
PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian
Rupee^$CostCenterId|4^10$LedgerId|2^3$
The position of current string ($CostCenterId|4^10) in the sequence may be change.
but it will always between the two $ sign.
I have written the below code, but confused abt what to write next ?
Public Sub GetSubstringData()
dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian
Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Dim CostIndex As Integer
CostIndex = sDiscription.IndexOf("CostCenterId")
sDiscription.Substring(CostIndex,
End Sub
Have a look into the Split function of a string. This allows you to split a string into substrings based on a specified delimiting character.
You can then do this:
Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Debug.WriteLine("$" + sfullString.Split("$"c)(3))
Result: $CostCenterId|4^10
You will probably want to do some error checking to make sure the string actually contains the data you expect though.
However looking at the data, what you have is a string containing key-value pairs so you would be better to have a property to hold the CostCenterId and extract the data like this:
Public Property CostCenterId As String
Public Sub Decode(ByVal code As String)
For Each pair As String In code.Split("$"c)
If pair.Length > 0 AndAlso pair.Contains("|") Then
Dim key As String = pair.Split("|"c)(0)
Dim value As String = pair.Split("|"c)(1)
Select Case key
Case "CostCenterId"
Me.CostCenterId = value
End Select
End If
Next
End Sub
Then call it like this:
Decode("PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$")
Why not split() the string by $ into an array, and then look for the element which contains CostCenterId
This should work:
Dim token = "$CostCenterId"
Dim costIndexStart As Integer = sfullString.IndexOf(token)
Dim costIndexEnd As Integer = sfullString.IndexOf("$", costIndexStart + token.Length)
Dim cost As String = sfullString.Substring(costIndexStart, costIndexEnd - costIndexStart + 1)
Result: "$CostCenterId|4^10$"
If you want to omit the dollar-signs:
Substring(costIndexStart + 1, costIndexEnd - costIndexStart - 1)
Try something like this:
Dim CostIndex As Integer
CostIndex = sDiscription.IndexOf("CostCenterId")
auxNum = sDiscription.IndexOf("$"c, CostIndex) - CostIndex
sResult = sDiscription.SubString(CostIndex, auxNum)
Your string,
Dim xString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Substring process,
xString = xString.Substring(xString.IndexOf("$CostCenter"), xString.IndexOf("$", xString.IndexOf("$CostCenter") + 1) - xString.IndexOf("$CostCenter"))
Try this Code:
Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian" _
& "Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Dim sp() As String = {"$"}
Dim ar() As String = sfullString.Split(sp, StringSplitOptions.RemoveEmptyEntries)
Array.Sort(ar)
MsgBox("$" & ar(0))

How i can get selected parts from string?

How i get string like
'EJ0004','EK0001','EA0001'
from string like
{Emaster.Emp_Code}='EJ0004' OR {Emaster.Emp_Code}='EK0001' OR {Emaster.Emp_Code}='EA0001'
in VB.NET?
You can use a regular expression.
Example:
Sub Main
Dim s = "{Emaster.Emp_Code}='EJ0004' OR {Emaster.Emp_Code}='EK0001' OR {Emaster.Emp_Code}='EA0001'"
Dim pattern = "('\w*')"
Dim matches = Regex.Matches(s, pattern)
Dim values = matches.OfType(Of Match).Select(Function(m) m.Value)
For Each v in values
Console.WriteLine(v)
Next
Console.WriteLine(String.Join(",", values))
End Sub
Output:
'EJ0004'
'EK0001'
'EA0001'
'EJ0004','EK0001','EA0001'
there are many ways you could do this, here i offer one simple way:
dim yourString as string = 'This is the variable which holds your initial string
dim newString as string = yourString.replace("{Emaster.Emp_Code}=", "").replace(" OR ",",")
Now newString will hold 'EA0001' Or whatever.
If you want it without the '' then do
dim newString as string = yourString.replace("{Emaster.Emp_Code}=", "").replace("'","").replace(" OR ",",")

Convert a string to decimal in VB.NET

What will be the easiest way to convert a string to decimal?
Input:
a = 40000.00-
Output will be
40,000.00-
I tried to use this code:
Dim a as string
a = "4000.00-"
a = Format$(a, "#,###.##")
console.writeline (a)
Use Decimal.Parse to convert to decimal number, and then use .ToString("format here") to convert back to a string.
Dim aAsDecimal as Decimal = Decimal.Parse(a).ToString("format here")
Last resort approach (not recommended):
string s = (aAsDecimal <0) ? Math.Abs(aAsDecimal).ToString("##,###0.00") + "-" : aAsDecimal .ToString("##,###0.00");
You will have to translate to Visual Basic.
For VB.NET:
CDec(Val(string_value))
For example,
CDec(Val(a))
The result will be 40000D or if the value for a = "400.02" then it will be 400.02D.
Use Decimal.TryParse
Dim a as string
Dim b as Decimal
If Decimal.TryParse(a, b) Then
a = b.ToString("##,###.00")
Else
a = "can not parse"
End If
The following works fine for me, but I don't know whether it is correct or not.
double a = 40000.00;
a = double.Parse(a.ToString("##,###.00"));
MessageBox.Show(a.ToString("##,###.00"));
Sub Main()
Dim convert As Func(Of String, Decimal) = _
Function(x As String) Decimal.Parse(x) ' This is a lambda expression.
Dim a = convert("-16325.62")
Dim spec As String = "N"
Console.WriteLine("{1}", spec, a.ToString(spec))
'Console.ReadLine() ' Uncomment to see value in Console output.
End Sub
Dim D# = CDec(TextBox1.Text) '//convert string to decimal with short
This code works, but it is quite long:
Dim a as string
Dim b as decimal
a = "4000.00-"
b = a
If b >= 0 then
console.writeline (b.ToString("##,###.00"))
Else
b = Math.Abs(b)
console.writeline (b.ToString("##,###.00") & "-")
End if

Left of a character in a string in vb.net

say if I have a string 010451-09F2
How to I get left of - from the above string in vb.net
I want 010451
The left function doesn't allow me to specify seperator character.
Thanks
Given:
Dim strOrig = "010451-09F2"
You can do any of the following:
Dim leftString = strOrig.Substring(0, strOrig.IndexOf("-"))
Or:
Dim leftString = strOrig.Split("-"c)(0) ' Take the first index in the array
Or:
Dim leftString = Left(strOrig, InStr(strOrig, "-"))
' Could also be: Mid(strOrig, 0, InStr(strOrig, "-"))
Dim str As String = "010451-09F2"
Dim leftPart As String = str.Split("-")(0)
Split gives you the left and right parts in a string array. Accessing the first element (index 0) gives you the left part.
Sorry not sure on the vb syntax, but the c# is
string mystring ="010451-09F2";
string whatIwant = mystring.Split('-')[0];
Get the location of the dash first (or do it inline), and use that value for the left. This is old school VBA, but it'll be something like this:
Left(YourStringWithTheDash, InStr(YourStringWithTheDash)-1)
dim s as String = "010451-09F2"
Console.WriteLine(s.Substring(0, s.IndexOf("-")))
Console.WriteLine(s.Split("-")(0))
Use something like this:
Mid("010451-09F2",1,InStr("-"))
Dim sValue As String = "010451-09F2"
Debug.WriteLine(sValue.Substring(0, sValue.IndexOf("-"c)))
This helped
Dim str1 as string = me#test.com
Dim str As String
str = Strings.Left(str1, str1.LastIndexOf("#"))