Friday, 15 March 2013

java - Reverse a String by reading from a txt file -



java - Reverse a String by reading from a txt file -

i trying reverse string. reading string field, called abc.txt

import java.io.bufferedreader; import java.io.filereader; import java.io.filewriter; import java.io.ioexception; import java.util.stringtokenizer; public class mrtext { private static final string new_line_separator = scheme .getproperty("line.separator"); public static void main(string[] args) throws ioexception, arrayindexoutofboundsexception { filereader input = new filereader("abc.txt"); bufferedreader bufread = new bufferedreader(input); stringbuffer rvswords = new stringbuffer(); string line; line = bufread.readline(); while (line != null) { stringtokenizer tok = new stringtokenizer(line); string linereversed = ""; while (tok.hasmoreelements()) { string word = (string) tok.nextelement(); (int = word.length() - 1; >= 0; i--) { rvswords.append(word.charat(i)); } } line = bufread.readline(); if (line != null) { rvswords.append(new_line_separator); } } bufread.close(); // file outfile = new file("gggggggggggggggggggg.txt"); filewriter author = new filewriter(outfile); writer.write(rvswords.tostring()); writer.close(); // system.out.println(rvswords.tostring()); // rvswords.setlength(0); } }

text file input: abc.text contains

it comp mech civil

output above code: ti pomc livic hcem

insted wanyt output: comp civil mech

you did not need loop (it reversing words)

take words straight , set them smartly in output :

stringbuffer rvswords = new stringbuffer(); string line; line = bufread.readline(); int index = 0; while (line != null) { stringtokenizer tok = new stringtokenizer(line); while (tok.hasmoreelements()) { string word = (string) tok.nextelement(); rvswords.insert(index, " "); rvswords.insert(index, word); } line = bufread.readline(); if (line != null) { rvswords.append(new_line_separator); } index = rvswords.length() - 1; }

java

No comments:

Post a Comment