Search code examples
autoitword-counttextselection

Why does my script return 0?


This AutoIt script counts number of words; characters (with and without spaces); lines; and estimated speaking time (assuming two words per second) for text selected by the user.

However, if the starting position is 0 for the input string (at the upper left-hand corner of the top of the file) the method returns 0 for everything, even when the main function works perfectly.

I cannot figure out why.

$input_str = GUICtrlRead($Textbox)
$selpos = _GUICtrlEdit_GetSel($Textbox)
MsgBox($MB_OK, $selpos[0], $selpos[1])
$selstring = StringMid($input_str, $selpos[0], ($selpos[1] - $selpos[0]))
$WordArray = StringRegExp($selstring, "[\s\.:;,]*([a-zA-Z0-9-_]+)[\s\.:;,]*", 3)
$SingleQuotes = StringRegExp($selstring, "'", 3)
$Result = ""
$Seconds = (UBound($WordArray) - UBound($SingleQuotes)) / 2

If $Seconds >= 3600 Then
    If $Seconds / 3600 >= 2 Then
        $Result = $Result & Int($Seconds / 3600) & " hours "
    Else
        $Result = $Result & Int($Seconds / 3600) & " hour "
    EndIf
EndIf

If Mod($Seconds, 3600) >= 60 Then
    If $Seconds / 60 >= 2 Then
        $Result = $Result & Int(Mod($Seconds, 3600) / 60) & " minutes "
    Else
        $Result = $Result & Int(Mod($Seconds, 3600) / 60) & " minute "
    EndIf
EndIf

If Mod($Seconds, 60) > 0 Then
    If Mod($Seconds, 60) >= 2 Then
        $Result = $Result & Int(Mod($Seconds, 60)) & " seconds "
    Else
        $Result = $Result & Int(Mod($Seconds, 60)) & " second "
    EndIf
EndIf
MsgBox($MB_OK, "Selection Properties", _
    "Number of characters (with spaces): " & StringLen($selstring) & @CRLF & _
    "Number of Characters (without spaces): " & StringLen(StringStripWS($selstring, 8)) & @CRLF & _
    "Number of words: " & (UBound($WordArray) - UBound($SingleQuotes)) & @CRLF & _
    "Number of lines: " & _GUICtrlEdit_GetLineCount($selstring) & @CRLF & _
    "Estimated speaking time: " & $Result _
)

Solution

  • If $selpos[0] = 0 then StringMid() returns an empty string since your start is out of bounds (as first position for StringMid() is 1).

    $sTest = "A sample test string"
    
    MsgBox(0, '' , StringMid($sTest , 0 , 8))
    MsgBox(0, '' , StringMid($sTest , 1 , 8))