Homework: Java IO Streaming and String

In Java, I need to read lines of text from a file, and then flip each line by writing the reverse version to another file. I know how to read from one file and write to another. What I do not know how to do is to manipulate the text so that "This is line 1" is written to the second file as "1 enil si sihT"

+3
source share
7 answers

If this is homework, you better understand how the data is stored in a row.

A string can be represented as an array of characters

String line =  // read line ....;
char [] data = line.toCharArray();

To cancel an array, you must swap the positions of the elements. First in last, last in first, etc.

int l = data.length;
char temp;

temp         = data[0];      // put the first element in "temp" to avoid losing it.
data[0]      = data[l - 1]; // put the last value in the first;
data[l - 1]  = temp;         // and the first in the last.

( ) , :

String modifiedString = new String( data ); // where data is the reversed array. 

( ), :

StringBuilder.reverse()

.

+2
StringBuilder buffer = new StringBuilder(theString);
return buffer.reverse().toString();
+2

, , , reverse.

( 0), StringBuilder:

public String reverse(String s) {
    StringBuilder sb = new StringBuilder();

    for (int i = s.length() - 1; i >= 0; i--) {
        sb.append(s.charAt(i));
    }

    return sb.toString();
}

, "hello":

H e l l o 
0 1 2 3 4  // indexes for charAt()

4 ('o'), 3 ('l')... 0 ('H').

+2
String reversed = new StringBuilder(textLine).reverse().toString();
+1

, , .

, . , for , , , .

+1

, . , , :

public static String reverse(String str) {
   if (str.length() == 0) return ""; 
   else return reverse(str.substring(1)) + str.charAt(0);
}

(, : Clojure, Lisp!)

BONUS HOMEWORK: , , !

+1

Source: https://habr.com/ru/post/1725185/


All Articles