Swap two strings in Java, by passing them to a utility function, but without returning objects or using wrapper classes

前端 未结 9 2240
既然无缘
既然无缘 2020-12-16 20:31

I am trying to swap two strings in Java. I never really understood \"strings are immutable\". I understand it in theory, but I never came across it in practice.

Also

9条回答
  •  一向
    一向 (楼主)
    2020-12-16 20:59

    By using StringBufferReader and StringBuilder this can be solved. At 1st get the values from the user then split them and store them in array. Run the for loop in the reverse order so that the last string will be appended and displayed 1st the first will displayed last. input:hello world output:

    import java.io.*;
    import java.util.*;
    import java.lang.*;
    public class Solution {
      public static void main(String[] args) {
        try {
          int s,i,j;
          StringBuilder str = new StringBuilder();
          String st,t;
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          t = br.readLine();
          s = Integer.parseInt(t);
          for (i = 0; i < s; i++) {
            st=br.readLine();
            String st1[]=st.split("\\s+");
            // System.out.println("l="+st1.length);
            for (j = st1.length - 1; j >= 0; j--) {
              str.append(st1[j] + " ");
            }
            System.out.println(str);
            str.setLength(0);
          }
        } catch (Exception e) {
          System.out.println(e);
        }
      }
    }
    

提交回复
热议问题