简体   繁体   中英

Reversing an entire paragraph of text instead of reversing each consecutive line

I was trying to read a text file using FileInputStream and wanted to display all of the words in reverse (so the last word will be the first word etc.) I was able to display all the letters in reverse using a string tokenizer, but not the words.. I've tried a few different methods now and just couldn't seem to do this

Using an ArrayList I could reverse the lines (print the last line first and the first line last).. but I couldn't find a way to reverse all the words

here is what is in my "test.txt" file:

One characteristic of Java is portability, which means that computer programs written in the Java language must run similarly on any hardware/operating-system platform. This is achieved by compiling the Java language code to an intermediate representation called Java bytecode, instead of directly to platform-specific machine code. Java bytecode instructions are analogous to machine code, but they are intended to be interpreted by a virtual machine (VM) written specifically for the host hardware. End-users commonly use a Java Runtime Environment (JRE) installed on their own machine for standalone Java applications, or in a Web browser for Java applets.

code:

import java.io.*;  
import java.util.ArrayList;


public class RevWords6
{
    public static void main(String[] args) throws IOException
    {   
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt"), "UTF-8"));                

        String lines = br.readLine();
        ArrayList<String> buffer = new ArrayList<String>();

        //while the data is not null
        while(lines != null)
        {   
            //String words[] = lines.split(" ");

            //track formatting
            if(lines != null)
            {   
                buffer.add("\n");
                buffer.add(lines);  //I wanted to put the words array in here instead of "lines" but didn't know how
            }

            lines=br.readLine();
        }

        //reads lines backwards from ArrayList buffer but wanted to read words from end-to-beginning
        for(int i = buffer.size()-1; i>=0; i--)
        {
            System.out.print(buffer.get(i));
        }

        br.close();
    }
}

output:

installed on their own machine for standalone Java applications, or in a Web browser for Java applets. by a virtual machine (VM) written specifically for the host hardware. End-users commonly use a Java Runtime Environment (JRE) bytecode, instead of directly to platform-specific machine code. Java bytecode instructions are analogous to machine code, but they are intended to be interpreted hardware/operating-system platform. This is achieved by compiling the Java language code to an intermediate representation called Java One characteristic of Java is portability, which means that computer programs written in the Java language must run similarly on any

As you can see it is printing the lines beginning from bottom to top, but I wanted the words beginning from bottom to top

and here I've tried to use a StringBuffer with a string array splitting the lines by one whitespace, but in this case I could only reverse each line and not reverse the entire paragraph

code:

import java.io.*;  


public class RevWords4
{   

    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\Conor\\Documents\\test.txt"), "UTF-8"));               
        StringBuffer buffer = new StringBuffer();   

        String line = br.readLine();
        String[] word = line.split(" ");

        while(line != null)
        {           
            if(line != null)
            {   
                word = line.split(" ");

                for(int i = word.length-1; i>=0; i--)
                {
                    StringBuilder sb = new StringBuilder(word[i] + " ");        
                    buffer.append(sb);          
                }

                buffer.append("\n");
            }

            line=br.readLine();
        }


        System.out.print(buffer);
        br.close();
    }
}

output:

any on similarly run must language Java the in written programs computer that means which portability, is Java of characteristic One Java called representation intermediate an to code language Java the compiling by achieved is This platform. hardware/operating-system interpreted be to intended are they but code, machine to analogous are instructions bytecode Java code. machine platform-specific to directly of instead bytecode, (JRE) Environment Runtime Java a use commonly End-users hardware. host the for specifically written (VM) machine virtual a by applets. Java for browser Web a in or applications, Java standalone for machine own their on installed

So I would happily accept any suggestions and tips on this, thank you

Modifying the while loop a little bit did the trick for me:

StringBuilder str = new StringBuilder();
String[] splitStr = lines.split(" ");
for (int i = splitStr.length; i > 0; i--) {
    str.append(splitStr[i - 1]).append(" ");
}

buffer.add(str.toString());  //I wanted to put the words array in here instead of "lines" but didn't know how

So, your complete code looks like this:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;


public class RevWords6
{
    public static void main(String[] args) throws IOException
    {   
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt"), "UTF-8"));                

        String lines = br.readLine();
        ArrayList<String> buffer = new ArrayList<String>();

        //while the data is not null
        while(lines != null)
        {   
            //String words[] = lines.split(" ");

            //track formatting
            if(lines != null)
            {   
                buffer.add("\n");

                StringBuilder str = new StringBuilder();
                String[] splitStr = lines.split(" ");
                for (int i = splitStr.length; i > 0; i--) {
                    str.append(splitStr[i - 1]).append(" ");
                }

                buffer.add(str.toString());  //I wanted to put the words array in here instead of "lines" but didn't know how
            }

            lines=br.readLine();
        }

        //reads lines backwards from ArrayList buffer but wanted to read words from end-to-beginning
        for(int i = buffer.size()-1; i>=0; i--)
        {
            System.out.print(buffer.get(i));
        }

        br.close();
    }
}

UPDATE Having a custom reader that reads a line reversed might be a slightly better approach:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;

public class ReversedLineBufferedReader extends BufferedReader {

    public ReversedLineBufferedReader(Reader in) {
        super(in);
    }

    @Override
    public String readLine() throws IOException {
        String line = super.readLine();

        if (line == null) {
            return null;
        }

        StringBuilder reversedLine = new StringBuilder();
        if (line.length() > 0) {
            String[] splitString = line.split("\\b");
            for (int i = splitString.length; i > 0; i--) {
                reversedLine.append(splitString[i - 1]).append(" ");
            }
        }
        return reversedLine.toString();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM