How best to compare string character

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
omar
Posts: 540
Joined: 22 Oct 2015, 17:56

How best to compare string character

11 Dec 2017, 15:28

I want to read in a string.

If the first character is NOT 0, then I want to do action xyz.

I wasnt sure what comparison operator to use for strings.

In this case, I'm using a number - in another case could be a letter - in which case, need to consider upper or lower case.

Thanks.
Osprey
Posts: 453
Joined: 18 Nov 2017, 05:50

Re: How best to compare string character

11 Dec 2017, 15:45

Try using the StringLeft command or the SubStr function.
Last edited by Osprey on 11 Dec 2017, 15:46, edited 1 time in total.
User avatar
Gio
Posts: 1247
Joined: 30 Sep 2013, 10:54
Location: Brazil

Re: How best to compare string character

11 Dec 2017, 15:46

Hello Omar.

The exclamation(!) can be used as a NOT operator in expressions. Example:

Code: Select all

String1 := "skjdhfkjs-23r2"
If !(SubStr(String1, 1, 1) = "0")
{
    msgbox % "First char of String1 is NOT 0" ; This will execute because the first char in string1 IS NOT 0.
}
String2 := "0skjdhfkjs-23r2"
If !(SubStr(String2, 1, 1) = "0")
{
    msgbox % "First char of String2 is NOT 0" ; This will NOT execute, because the first char in string2 IS 0.
}
omar
Posts: 540
Joined: 22 Oct 2015, 17:56

Re: How best to compare string character

11 Dec 2017, 22:56

thanks guys
@Gio... this is the stumbling point for me...
Why a single =?
And why have the ! outside?
Cant you have if(A != B) ?
I assume what I'm saying is wrong - it's just the way on AHK? Just seems odd to me
Osprey
Posts: 453
Joined: 18 Nov 2017, 05:50

Re: How best to compare string character

12 Dec 2017, 01:11

If you mean why he doesn't use ==, he's just comparing to 0, and = and == behave identically with numbers. If you expand the code to consider strings and case sensitivity is important, then you might want to change that to == (or toggle StringCaseSense).

As for having the ! on the outside, you could certainly put it on the inside, but having it in the front makes it easy to spot. If you were want to reverse the statement, you wouldn't have to scan the statement to find the equal sign. You'd simply remove the !, instead. In other words, my guess is that it's just a matter of form and personal preference that Gio chose to write it like that.

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: FanaticGuru, filipemb, Google [Bot], LRRUNB and 238 guests