views:

261

answers:

7

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

+2  A: 

If this is homework, it would be better for you to understand how are data stored into the string it self.

A string may be represented as an array of characters

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

To reverse an array you have to swap the positions of the elements. The first in the last, the last in the first and so on.

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.

Continue with the rest of the elements ( hint use a loop ) in the array and then create a new String with the result:

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

If is not ( and you really just need to have the work done ) use:

StringBuilder.reverse()

Good luck.

OscarRyz
+2  A: 
StringBuilder buffer = new StringBuilder(theString);
return buffer.reverse().toString();
Nick Hristov
@Nick: if your surround your code snippet with pre and code tags, you'll get better readability (and possibly more upvotes :).
CPerkins
Ah, yes, I just saw that. Sorry, I am new, still learning the site...
Nick Hristov
No worries, and welcome to the party.
CPerkins
+1  A: 
String reversed = new StringBuilder(textLine).reverse().toString();
Bozho
A: 

java.lang.StringBuffer has a reverse method.

Robert Christie
+1  A: 

The provided answers all suggest using an already existing method, which is sound advice and usually more effective than writing your own.

Depending on the assignment, however, your teacher might expect you to write a method of your own. If that is the case, try using a for loop to walk through the string character by character, only instead of counting from zero and up, start counting from the last character index and down to zero, consecutively building the reversed string.

Jakob
+2  A: 

since these are homeworks you are probably interested in your own implementation of reverse method.

The naive version visits the string backwards (from the last index to the index 0) while copying it in a 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();
}

for example the String "hello":

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

the method start by the index 4 ('o') then the index 3 ('l') ... until 0 ('H').

dfa
@downvoter: your vote is pointless without a comment
dfa
+1  A: 

While we're feeding horrible, finished answers to the poor student, we might as well whet his appetite for the bizarre. If strings were guaranteed to be reasonably short and CPU time was no object, this is what I'd code:

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

(OK, I admit it: my current favorite language is Clojure, a Lisp!)

BONUS HOMEWORK: Figure out if, how and why this works!

Carl Smotricz
Fun solution, except for the performance issue of string concatenation, which should really use a StringBuilder
Sam Barnum
Definitely, that's why I qualified "CPU time no object" :) Using a StringBuilder would have resulted in lengthier code though. That's not what I was optimizing for.
Carl Smotricz
And unfortunately the stack overflow potential is the far more serious problem. :(
Carl Smotricz