How do I make a conditional if by comparing only the last 2 digits?

Asked

Viewed 87 times

5

I am doing a project in Visual Basic but when the user type a string that will be 5 the maximum ex: UF052 I want to do a if where it will be compared.

If textbox1 = "UF052" the
  Comando
End if

However I do not want to compare all the characters but only the 52 could be UG152 that would still fall in the true.

3 answers

4

You can compare the last two characters of your string without manipulating and create a new string:

If(textBox1(textBox1.Length - 2) = "5"C And textBox1(textBox1.Length - 1) = "2"C)
    Comando

2

Good afternoon, use the "Instr" that will work too. Follow example:

if InStr("UF052", "52") > 0 then 
    Comando
End if

or if you want to pick only the last two characters:

if InStr(Right("UF052", 2), "52") > 0 then 
    Comando
End if
  • 1

    It could improve the condition by going to InStr() to position where you want to start the search (in this case the last two digits of the string).

  • yes, if his string always comes "UF052" he can impose the position. Example: Instr(Right("UF052", 2), "52")

  • 1

    According to the OP, he always wants to check the last two characters of string hence my suggestion. In this case it is not problematic because, according to the OP, the string has a maximum of 5 characters, so the impact on performance is minimal.

  • I changed my comment...

  • yes, in fact the UF will always have this value I will set UF already at the beginning the user will type only for example 654 or other value, I can do with variables tbm? , because I will not know which value q the user will type, will have a textbox2 that will appear these UF*** at a certain time then when arriving this UF*** equal to the user would enter true.

  • You have Ixxtomxxi, instead of the string you put a string type variable.

Show 1 more comment

2

Use the Substring. Example:

Dim text As string = "Olá mundo!"
Dim teste As Boolean = text.Substring(text.Length - 2) = "o!"

Console.WriteLine(teste) //True
Console.WriteLine(text.Substring(text.Length - 2)) //o!

Even better to use the EndsWith

Dim text As string = "Olá mundo!"
Dim teste As Boolean = text.EndsWith("o!")

Console.WriteLine(teste) 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.