0

Let's say i have a String which is like "Hello this is %d next year is %d" or "I am in %d and we will be in %d".

Now I have to replace first %d with current year and second %d with next year.

The final String should be

"Hello this is 2021 next year is 2022" 
"I am in 2021 and we will be in 2022".

I tried using split and streams, but that didn't really work.

The below approach didnt work

  List<String> myList= new ArrayList<>();
      myList.add("Hello is %d and %d");
      myList.add("Hello this is %d and %d");
      for(String s: myList)
      {
          String.format(s,2021,2022);
          System.out.println(s);

      }
Satya ram
  • 67
  • 3
  • 8
  • 1
    Something like `String.format("Hello this is %d next year is %d", 2021, 2022)`? – Pshemo Jun 06 '22 at 17:45
  • @Pshemo I have a list of Strings in my case List myList= new ArrayList<>(); myList.add("Hello is %d and %d"); myList.add("Hello this is %d and %d"); for(String s: myList) { String.format(s,2021,2022); } – Satya ram Jun 07 '22 at 06:47
  • I tried the approach you suggested, which didnt actually quite work – Satya ram Jun 07 '22 at 06:48
  • *Strings are immutable* so `String.format(s,2021,2022)` doesn't *modify* `s` but creates new one based on received data. Then `String.format(s,2021,2022);` *returns* that new String. But it doesn't *print it automatically*, it is up to you what to do. Problem is you don't do anything with it. If you want to print it you can use `System.out.println(String.format(s,2021,2022));` or shorted `System.out.printf(s,2021,2022);`. – Pshemo Jun 07 '22 at 12:26

0 Answers0