Substring not working
SOLVED- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Substring not working
I am trying to output the first X characters of a XML response and getting error.
Line in the code below, MESSAGE2 can be very long and I like to output only the first 40 characters.
Please help.
def xmlResponse = tStep.getPropertyValue("Response")
def holder = groovyUtils.getXmlHolder(xmlResponse)
def MESSAGE1 = holder.getNodeValue("/S:Envelope/S:Body/ns2:changeMsisdnResponse/resultData/errorCode")
def MESSAGE2 = holder.getNodeValue("/S:Envelope/S:Body/ns2:changeMsisdnResponse/resultData/message")
MESSAGE3 = substring( MESSAGE2, 0, 39)
log.info MESSAGE1 + " " + MESSAGE3
Solved! Go to Solution.
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Hi,
Substring is a method of the string class. You cannot call it directly.
Try...
MESSAGE3 = MESSAGE2.substring(0, 39)
For more details, have a look at the Groovy docs.... https://www.tutorialspoint.com/groovy/groovy_substring.htm
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
I tried this and it is working:
int str_len = MESSAGE2.length()
if (str_len>92) { MESSAGE2 = MESSAGE2.substring(0,91) }
In this method, I have to determine the length of the string first.
Is there a way I can yield the same result without knowing the length first?
In other words, I like to output the first 92 characters of MESSAGE2. If MESSAGE2 has less characters, output the whole string.
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Hi,
I honestly cannot think of a way to use an 'if' against string length decision without calculating the length.
Your approach looks good, but if its making it more concise that you're after, then try...
if ( MESSAGE2.length() > 92 ) { MESSAGE2 = MESSAGE2.substring(0,91) }
You might want to have a read about Ternary operators (https://groovy-programming.com/post/175536037619) which are very concise conditionals, but you'll still need to work out the length.
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
if ( MESSAGE2.length() > 92 ) { MESSAGE2 = MESSAGE2.substring(0,91) }
Yes, this is better. I will use this. Thanks.
I found this but it does not work for me. This function does not require string length in advance.
StringUtils.substring("abc", 2, 4) = "c" StringUtils.substring("abc", 4, 6) = ""
