AutoHotkey – StrSplit()
StrSplit() splits strings into parts.
Parameters
StrSplit( String, Delimiter, Omitchars, Maxparts )
- String: the string you want to split
- Delimiter: this character or string (characters) will split the string
- Omitchars: characters can be omitted
- Maxparts: default is -1 = “no limit”, a limit can be set
Return value
The function returns an array.
Examples
Separate sentences by the period character.
Strg := "Welcome. I am Bence."
Sentences := StrSplit(Strg, ".")
for key, value in Sentences
MsgBox % "The " key ". sentence is: " value "."
Direct access to a value by key.
Sentences := StrSplit("Hello. Hi Everyone.")
MsgBox % "Sentence 1:" "`n`n" Sentences[1]
MsgBox % "Sentence 2:" "`n`n" Sentences[2]
MsgBox % "Sentences:" "`n`n" Sentences[1] " " Sentences[2]
Access to the last value
example := "x=100|y=100|w=300|h=400"
example := strSplit(example, "|")
; this will display nothing, since strg is an array by now
Msgbox % (e := example) "It's OK, you can't see the array's content this way."
MsgBox % "Yeeey, both look good!" "`n`n" example.1 "`t" e.2 "`t" e[3] "`t" e.4
MsgBox % "The last value is:" Example[Example.Length()]
How many values are stored in the array ( MaxIndex(), Length(), Count() )
strg := "Apple,Banana,Cherry"
strg := strSplit(strg, ",")
MsgBox % "The max index is: " strg.MaxIndex() "`n"
. "The length is: " strg.Length() "`n"
. "The count is: " strg.Count()
String separation with space character
Fruits := StrSplit((orig:="Apple Banana Strawberry"), " ")
Direct1 := StrSplit(Fruits, " ")[1]
Direct2 := StrSplit(Fruits, " ").2
MsgBox % "Original string`n`n" orig "`n`n"
. "Fruits.1" "`t" fruits.1 "`n"
. "Fruits[1]" "`t" fruits[1] "`n"
. "Direct[1]" "`t" Direct1 "`n"
. "Direct.2" "`t" Direct2
This is also a less-known trick, StrSplit without using a delimiter
Letters := "ABCDEFG"
for key, value in StrSplit(Letters)
MsgBox % "Key " key ", " "Val " value
MsgBox % "There are " Letters.MaxIndex() " letters." "`n"
. "The third letter is: " Letters.3 "." "`n"
. "The last is: " Letters[Letters.Length()] "."