Add "0" in front of one digit string

 

 

Hi 

 

 

I have a string column below

 

String data   

1

2

3

11

12

13

 

 

What I want to do is to add "0" in front of the the sting with only one character so "1" will be "01" for sorting forpuse.

 

Thanks in advance

Hi 

One way would be to use the Java Snippet node:

Declare a custom variable (String Zero), either append or replace the column as an output and add the custom variable to the String Data column:

// Your custom variables:
String zero ="0";
// expression start
  
// Enter your code here:

out_sss = zero + c_String_data;

// expression end

In a simple snippet, you can alternatively used the string fromat method:

return String.format("%02d",Integer.parseInt($column1$));

(where column1 is your string column)

If you precede the node by a string to number node, and convert to IntCell, then even simpler:

return String.format("%02d",$column1$);

Steve

return String.format("%02d",$column1$);

How to use this in KNIME I am getting an error mentioning " Void method cannot return a Value"

Hi @namankumar169,

I am not sure what causes your error. It might be an invalid input, you would need to give us some more information, maybe you can post the workflow?

However, another easy way to solve this task is using the Column Expressions node with this script:

if (length(column("column1"))<2) {
    "0" + column("column1")
} else {
    column("column1")
}

column1 must be replaced by your column name. Here is also an example workflow:add_leading_0.knwf (6.2 KB)

Cheers,
Simon

6 Likes

I am going to close this topic since you have opened a new one.

1 Like