0

How to Extract only string using For loop. For attached code: Expected Result: A0, A1, A2

Actual Result: null, A0, A1, A2

def s = new String[3] 
s[0]="A0" 
s[1]="A1" 
s[2]="A2"  

def myString 
for(def i=0; i<s.size(); i++){ 
  str = s[i] 
  myString = myString + ", " + str 
} 

log.info "Final String: " +myString
Shayan Shafiq
  • 1,447
  • 5
  • 18
  • 25
kumar
  • 13
  • 3
  • 2
    Add log.info() inside your loop to debug and understand your bug – tkruse Jan 23 '21 at 01:32
  • Sorry, I am very new to coding. command 'def myString' is creating a 'null' in result, but I am not expecting null in my result. Can anyone please help? – kumar Jan 23 '21 at 12:38
  • Please don't use screenshots, where text would do. We can not search in or copy from screenshots. – cfrick Jan 23 '21 at 12:47
  • Can you please help how to extract only strings using For_loop. Below is my code: **Expected Result:** A0, A1, A2 **Actual Result:** null, A0, A1, A2 `def s = new String[3] s[0]="A0" s[1]="A1" s[2]="A2" def myString for(def i=0; i – kumar Jan 23 '21 at 12:59
  • Please edit the question next time and add the code there. Comments are a bad place for that. – cfrick Jan 23 '21 at 13:13
  • As already stated: print `myString` inside the loop and you will see the problem. Yet this code is just `["a","b","c"].join(", ")` – cfrick Jan 23 '21 at 13:15
  • myString would be null to begin with. Initialise it to an empty string – JGFMK Jan 23 '21 at 13:29
  • Thank you, but my requirement is to print the result (A0, A1, A2) using for-loop, please help me what I have done wrong in my above code ? – kumar Jan 23 '21 at 13:32
  • Thank you, I have initialised the myString as empty string, but my result is (,A0,A1,A2). The problem is I can see the Comma before 'A0' which is not my requirement. My Updated code is below: `def s = new String[3] s[0]="A0" s[1]="A1" s[2]="A2" def myString="" for(def i=0; i – kumar Jan 23 '21 at 13:41
  • See https://stackoverflow.com/questions/599161/best-way-to-convert-an-arraylist-to-a-string – tkruse Jan 23 '21 at 14:00

0 Answers0