Elements of an arraylist as replacement in a files line

I have this part of the code which reads a file linebyline. This original line that is about to be edited is: j(ac) “test” /Aaa,Bbb/

I have an arraylist with elements [Ccc,Ddd,Eee] and I want these elements to be replaces in the line above between / and /. The replcement between / and / works fine. However I cant put the arraylist straight to the .replace cause [] will also appear. So I am tryin to add the elements of the list. However I cant get the desired result which is: j(ac) “test” /Ccc,Ddd,Eee/

I keep getting only the first element: j(ac) “test” /Ccc/

How could I fix this?

List<String> strlist = new ArrayList<String>() ;

Scanner scanner = new Scanner(file);

 while (scanner.hasNextLine()) {
               String line = scanner.nextLine();

               if (line.contains("j(ac)")) {   

                   String skat ;
                   skat = null ;

                   for(String s : strlist) {
                   for (int index = 0; index < strlist.size(); index++) {

                               s = strlist.get(index);
                       skat=s;
                   }
                   }
                  String next = line.replaceAll("/.*?/", "/"+skat+"/");

                   System.out.print(next);


               }

Answer

You’re very close.

You just need to change,

skat=s; to skat = skat + "," + s;

this way you’ll append to your list, add your commas, and not reset skat every iteration.

Leave a Reply

Your email address will not be published. Required fields are marked *