Comparing strings in VB.NET - vb.net

Hopefully this should be an easy question. In Java I think it's compareTo().
How do I compare two string variables to determine if they are the same?
ie:
If (string1 = string2 And string3 = string4) Then
'perform operation
Else
'perform another operation
End If

I would suggest using the String.Compare method. Using that method you can also control whether to have it perform case-sensitive comparisons or not.
Sample:
Dim str1 As String = "String one"
Dim str2 As String = str1
Dim str3 As String = "String three"
Dim str4 As String = str3
If String.Compare(str1, str2) = 0 And String.Compare(str3, str4) = 0 Then
MessageBox.Show("str1 = str2 And str3 = str4")
Else
MessageBox.Show("Else")
End If
Edit: If you want to perform a case-insensitive search you can use the StringComparison parameter:
If String.Compare(str1, str2, StringComparison.InvariantCultureIgnoreCase) = 0 And String.Compare(str3, str4, StringComparison.InvariantCultureIgnoreCase) = 0 Then

In vb.net you can actually compare strings with =. Even though String is a reference type, in vb.net = on String has been redefined to do a case-sensitive comparison of contents of the two strings.
You can test this with the following code. Note that I have taken one of the values from user input to ensure that the compiler cannot use the same reference for the two variables like the Java compiler would if variables were defined from the same string Literal. Run the program, type "This" and press <Enter>.
Sub Main()
Dim a As String = New String("This")
Dim b As String
b = Console.ReadLine()
If a = b Then
Console.WriteLine("They are equal")
Else
Console.WriteLine("Not equal")
End If
Console.ReadLine()
End Sub

Dim MyString As String = "Hello World"
Dim YourString As String = "Hello World"
Console.WriteLine(String.Equals(MyString, YourString))
returns a bool True. This comparison is case-sensitive.
So in your example,
if String.Equals(string1, string2) and String.Equals(string3, string4) then
' do something
else
' do something else
end if

I know this has been answered, but in VB.net above 2013 (the lowest I've personally used) you can just compare strings with an = operator. This is the easiest way.
So basically:
If string1 = string2 Then
'do a thing
End If

I think this String.Equals is what you need.
Dim aaa = "12/31"
Dim a = String.Equals(aaa, "06/30")
a will return false.

If String.Compare(string1,string2,True) Then
'perform operation
EndIf

Related

Comparing strings in a loop using Is Operator

Is Operator works fine when comparing two strings like:
Dim str1 As String = "TagnameX"
Dim str2 As String = "TagnameX"
Dim strChk as boolean = str1 Is str2
'strChk returns True
But when one of the strings is extracted by Substring it returns false ! as below:
Dim str1 As String = "t#1TagnameX"
Dim str1Extract As String = str1.Substring(3, 8)
Dim strArr() = {"Tagname1", "Tagname2", "TagnameX"}
For i = 0 To strArr.Length - 1
If strArr(i) Is str1Extract Then
MsgBox("TagnameX found!")
else
MsgBox("TagnameX was not found!")
End If
Next
'TagnameX was not found!
so am i using it wrong in some how? thanks for your help! :)
The Is-operator returns whether two references are equal: that is, whether the two variables refer to the same location in memory.
The first code snippet returns True because for literal strings, .NET interns duplicates rather than keeping separate identical copies in memory, so str1 and str2 refer to the same string in memory.
The second code snippet returns False because .NET does not necessarily intern intermediate strings, such as strings returned by Substring. So the variables str and strExtract do not refer to the same string.
You should use the equals operator = to compare the value of two strings.
I don't think that the Is operator does what you think it does.
The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons.
https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/is-operator
Instead just use = to compare string values.
If strArr(i) = str1Extract Then

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)

VB.net Function returning inconsistent results

I created a simple function designed to remove a string of characters from another string and replace it with what ever string the user wants (or no string as a default)
Private Function RemoveString(scontainer As String, Optional rcontainer As String = "", Optional rstring As String = "") As String
Dim container As String = scontainer
Dim tcontainer As String
If InStr(container, rcontainer) <> 0 Then
Do While (InStr(container, rcontainer) <> 0)
tcontainer = Microsoft.VisualBasic.Left(container, InStr(container, rcontainer) - 1)
tcontainer = tcontainer & rstring & Microsoft.VisualBasic.Right(container, (Len(container) - (InStr(container, rcontainer) + 2)))
container = tcontainer
Loop
RemoveString = container 'return modded string
Else
RemoveString = scontainer 'return string as is
End If
End Function
The problem is:
While this is suppose to be a general use function, I really need it to be concerned with 2 different strings
%20
amp;
the function works perfectly for the %20 situation but it leaves the semi-colon behind for the amp; string. Any ideas why this might be?
Do I get you right ?
You want to replace a certain char sequence in your string with another char sequence or just delete it.
If thats the case you could use String.Replace(oldValue As String, newValue As String) As String
Dim startString as String = "%20 amp;"
Dim resultString as String = startString.Replace("%20 ",String.Empty)
resultString = resultString.Replace(";",String.Empty)
After these lines resultString would be "amp"

Passing a string to a database with ToUpper? VB.NET 2010

I'm trying to validate a textbox. If user enters all lower case characters then convert it to all upper case. So when its added to the database its all upper case. I need help with my function, I don't know if its a syntax error or something, here it is. I'm using VB.Net 2010
Public Function CheckLetters(ByVal strIn As String) As Boolean
Dim i As Integer
Dim strOne As String
For i = 0 To Len(strIn) - 1
strOne = strIn.Substring(i, 1).ToUpper
Select Case strOne
Case "A" To "Z"
Case Else
Return False
End Select
Next
Return True
End Function
How 'bout this:
Return Regex.IsMatch(strIn, "^[a-z]*$")
or this
Return strIn.All(Function(c) Char.IsLower(c))
There's no good reason for this method to be anything other than a one-liner. But if you really want to loop through the characters:
For Each c As Char In strIn
If Not Char.IsLower(c) Then Return False
Next c
Return True
Your code runs just fine here (VB does not require the brackets after ToUpper, but it's good for readability) - it accepts a string and returns True if that string only contains the characters "A" through "Z", false otherwise. The function doesn't convert anything - just returns that Boolean result.
If you want to actually convert the string to upper case, just use .ToUpper() on the string itself, e.g.
Dim MyString As String = "Contains some text"
MyString = MyString.ToUpper()
' Above would set MyString to "CONTAINS SOME TEXT"

Is there any way to deal with ParamArray values as byRef so they can be updated?

Sounds simple enough, but its not working. In this example, I want to set the values of 3 fields to equal a 4th. I could do something like this....
Dim str1 As String = "1"
Dim str2 As String = "2"
Dim str3 As String = "3"
Dim str4 As String = "4"
str2 = str1
str3 = str1
str4 = str1
... but that's kind of wordy (yeah, I know, vb is wordy in most cases). I would like to have something I can use to reduce this to a single line call, so I made this extension method.
Module Module1
Sub Main()
Dim str1 As String = "1"
Dim str2 As String = "2"
Dim str3 As String = "3"
Dim str4 As String = "4"
Console.WriteLine("Extension method return value = {0}", str1.SetEqual(str2, str3, str4))
Console.WriteLine("String 1 = {0}", str1)
Console.WriteLine("String 2 = {0}", str2)
Console.WriteLine("String 3 = {0}", str3)
Console.WriteLine("String 4 = {0}", str4)
Console.ReadKey()
End Sub
<System.Runtime.CompilerServices.Extension()> _
Public Function SetEqual(Of T)(ByVal source As T, _
ByVal ParamArray targets() As T) _
As T
For _index = 0 To targets.Length - 1
targets(_index) = source
Console.WriteLine("Target Value {0} = {1}", _index, targets(_index))
Next
Return source
End Function
End Module
Seems straightforward enough, right? Well, the output is this...
Target Value 0 = 1
Target Value 1 = 1
Target Value 2 = 1
Extension method return value = 1
String 1 = 1
String 2 = 2
String 3 = 3
String 4 = 4
Values in the param array did not get updated in the return! I was expecting to have all of the final values now be "1", like they are in the Function.
Is there any way to get an update-able ParamArray collection like this? ParamArray must be declared ByVal, but with a reference type like String, shouldn't that only make a copy of the pointer and allow me to change the underlying value?
Is there a better way to get what I want? (C# is not an option for this).
What you're trying to do cannot be achieved with ParamArray. When you call a ParamArray method the following occurs under the hood
CLR allocates an array of appropriate length
The values are then copied into the array
Array is passed down into the function
There is no post call operation that will copy the values back out of the array and into the original variables that were passed in.
The only reliable way to have the function modify a value and have it seen at the call site is to pass the value ByRef. You could do a bit of magic to have a set of overloads which take ByRefs, manually convert to an array and then does a copy back. But that's the closest you're going to get.
Might be a bit late for case in point (almost 10 years ago) but might help someone else if it works...
You cannot pass parameter-array as reference, but you can pass an array as reference.
Change it to ByRef and remove ParamArray
Then modify this line:
Console.WriteLine("Extension method return value = {0}", str1.SetEqual({str2, str3, str4}))
Just take note of the additional "{" and "}" to pass strings as Array rather than ParamArray
I used this in a class to pass an array of controls and it worked (where ParamArray did not) so I'm hoping (cannot test it here) but it might be worth a shot