3

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"

13
  • 2
    The best person to ask would be your TA or professor. Commented Dec 9, 2009 at 17:05
  • 7
    Still a valid question, even on stack overflow Commented Dec 9, 2009 at 17:07
  • 1
    No, it's a terrible, lazy, worthless question, the badness of which is exceeded only by the answers from people who should know better. Commented Dec 9, 2009 at 17:09
  • 1
    I'm under the impression that the title on "downvote" is "The answer is not useful", not "There is a possibility that wrong moral points are taken". Commented Dec 9, 2009 at 17:23
  • 1
    @Oscar - google.com/… in this case, I'm not agreeing with you :) Commented Dec 9, 2009 at 17:23

7 Answers 7

2

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').

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@Nick: if your surround your code snippet with pre and code tags, you'll get better readability (and possibly more upvotes :).
2

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.

Comments

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

Comments

1

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.

Comments

1

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!

3 Comments

Fun solution, except for the performance issue of string concatenation, which should really use a StringBuilder
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.
And unfortunately the stack overflow potential is the far more serious problem. :(
-1

java.lang.StringBuffer has a reverse method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.