Count of "Segments" in a Split String

openHAB 2.4.0~20181105174706-1 (Build #1413)

Is it possible to get a count of the number of “segments” when using myString.split(";") so I know how many there are?

I have been using a concatenated string to pass two parameters to a Rule as

myItem.postUpdate("parameter1;parameter2")

and having the Rule trigger on the change in the Item.

I want to update my logic to have an optional third parameter and have the Rule “extract” the third parameter if it’s present or set a hard-coded value if the parameter is not passed. The problem is that if a third parameter is not present, a .get(2) raises an exception… as it should.

I know that there are lots of ways I could pass parameters to the Rule… but I’ve already gone down this route (i.e., passing parameters as a concatenated string) and used it in many Rules. I could have a different method to pass this third optional parameter, of course. But then the coding is inconsistent.

Is there a “concise” method of querying the number of concatenated segments or counting the number of delimiters present?

Thanks.

Mike

If i am right split returns an array so it should be possible to to write split(xxx).length, but this is not tested

1 Like

@Dibbler42
It works:

rule "String Test"
when
    Item TestString changed
then
    logInfo("TEST", TestString.state.toString.split(";").length.toString)
end
2019-01-10 17:08:32.727 [vent.ItemStateChangedEvent] - TestString changed from asd;ery;asd to asd;ery;asb
2019-01-10 17:08:32.825 [INFO ] [.eclipse.smarthome.model.script.TEST] - 3
2019-01-10 17:09:17.554 [vent.ItemStateChangedEvent] - TestString changed from asd;ery;asb to asd;ery
2019-01-10 17:09:17.555 [INFO ] [.eclipse.smarthome.model.script.TEST] - 2
2019-01-10 17:09:37.708 [vent.ItemStateChangedEvent] - TestString changed from asd;ery to asd;ery;asdgasg;swtryh
2019-01-10 17:09:37.702 [INFO ] [.eclipse.smarthome.model.script.TEST] - 4
3 Likes

Sweet!