Hello, help. I read a line from a file and now I need to break it into words by a space, just in the word swap letters and write to a file. How can you break into words and swap letters (no matter what, just for example)?

public static void main(String[] args) throws IOException { String text = new String(); Scanner in = new Scanner(new File("text.txt")); while (in.hasNext()) { text += in.nextLine(); } in.close(); char[] words; char line; String delimeter = " "; words = text.toCharArray(); FileWriter writer = new FileWriter("crypt.txt"); for (int i = 0; i < words.length; i++) { if(words[i] == ' ') { System.out.print(words[i]); break; } } } 

I tried to print at least the first letters before the space, but it did not work.

  • one
    Study assignments are allowed as questions only under the condition that you tried to solve them yourself before asking a question. Please edit the question and indicate what caused you difficulties in solving the problem. For example, give the code you wrote trying to solve the problem - Victor
  • one
  • "swap letters" how to swap, the third letter on the fifth, and the first on the second? - Victor

2 answers 2

You can swap letters using charAt ([0]) for example, or print them in the reverse order as in the example

 public class Main { public static void main(String[] args) { String s = "am arr"; String[] arrayStr = s.split(" "); for (String i : arrayStr) { String t = new StringBuilder(i).reverse().toString(); System.out.println(t); } } 

}

    So you can break the line through the spaces, if I understand you correctly)

      class Ideone { public static void main (String[] args) throws java.lang.Exception { for(char c: "Hello World".toCharArray()) { System.out.print(c + " "); //Output H ello W orld } } }