add characters to a string to make it constant length

One Star

add characters to a string to make it constant length

Hi,
I have a sting which carries multiple codes so if it has one code, its length is 4 if it has to codes its length is 8 if 3 then 12.
I want to add 0000 wherever a code is absent so that I can parse the code into strings of 4 characters using substring() in tmap.

Thanks,
Karan
One Star

Re: add characters to a string to make it constant length

Hi Karan
Could you explain it in another way?
Regards,
Pedro
One Star

Re: add characters to a string to make it constant length

Sure.
Below is what I want to achieve and I am using substing(0,4) & substring (4,8) in tmap to generate output fields 1 & 2 respectively.
1)input field1:AAAABBBB >> Output field1: AAAA Output field2:BBBB
2)input field1:CCCC >> Output field1: CCCC Output field2:<null>
3)input field1Smiley Very HappyDDD0000 >> Output field1: DDDD Output field2:0000
but since the input field in 2nd row is only 4 characters long, it goes "string index out of bounds" while generating output field2 since the length is 4 & not 8.
So I wanted to convert inout field1 in row 2 from CCCC to CCCC0000 so that it gets treated as row 3.

Since there are only 11 instances of 4 character long values, I tried to use if else in tmap but it is not giving the desired output.It always gives the input as output. My expression is as below
StringHandling.LEN(row3.SIC_CD) == 4 ? row3.SIC_CD + "0000" : row3.SIC_CD

Thanks,
Karan
One Star

Re: add characters to a string to make it constant length

Hi,
I think you want to right pad your strings with a "0" character. Use the Commons Lang StringUtils class that's available. This function right pads a string to 7 characters.
StringUtils.rightPad("CCCC", 7, "0");
This post shows how to access the Lang JAR that's provided with Talend.
http://bekwam.blogspot.com/2011/01/java-libraries-in-talend-open-studio.html
One Star

Re: add characters to a string to make it constant length

Thanks for the response.
This one is hard coded to add padding to "CCCC" how can I switch it to add padding only if the length is 4?
I have a head start at this by using the expression
StringHandling.LEN(row3.SIC_CD) == 4 ? row3.SIC_CD + "0000" : row3.SIC_CD
Unfortunately it is not giving the desired output. It gives
AAAABBBB
CCCC
DDDD0000
I want
AAAABBBB
CCCC0000
DDDD0000

Best,
Karan
One Star

Re: add characters to a string to make it constant length

I'm not sure why LEN isn't working for you. I put up a blog post on how to pad a string with StringUtils.rightPad: http://bekwam.blogspot.com/2012/04/right-padding-string-with-talend-open.html.