Truncate String to 160 charaters

I need to truncate a string to first 160 characters to send it via SMS.
I tried this code:

if (messaggio.length() > 160) {
            messaggio=messaggio.substring(0, 160);

But with this code into my rule, execution of the rule stop and do not go on.

How can I truncate string to 160 characters?

Many Thanks for help

Hi I did more testing and seem .substring(x,x) does not work anymore with OpenHab 2.
Is there a new way to perform substring?

Many Thanks

Is messaggio a val or a var?

substring should still work.

Note: you probably want substring(0,159) to get 160 characters instead of 161.

Hi @rlkoshak,
the definition of the string is

var String messaggio = ""

And when I run substring in a rule, rule stop to execute at the point where substring is.


Hi @marcolino7,

I think it is not working because messagio is an object and you only need the state formatted as a string. It should work with the following code:

if (messaggio.state.toString.length() > 160) {
            postUpdate(messagio, messaggio.state.toString.substring(0, 160))


P.S.: Not sure if you need the brackets after length :slight_smile:

Edit: sorry, didn’t read your last post. But here with me substring is working in OH2 correctly, Do you have the variable definition in the same rule? I always got problems when the variables are defined outside of the rule.

1 Like