"Java" word reverse output

Source: Internet
Author: User
Tags stringbuffer

How do I output a word in reverse? Turn "Hello java hello China" into "China hello java hello"?

It seems very simple, just want to divide the string into words first, then add a StringBuilder or StringBuffer, and finally use the ToString method, now to achieve:

/** * @authorFrank * @create 2017/11/24 * @description*/ Public classTest { Public Static voidMain (string[] args) {String src= "Hello Java hello China";//strings that need to be processedstring[] arr = Src.split ("");//Split by Space        intlength = Arr.length;//calculating the length of an arrayStringBuilder SB =NewStringBuilder (Src.length ());//Create a new StringBuilder object         for(inti=length-1;i>=1;i--) {sb.append (Arr[i]+" ");//add string to StringBuilder in sequence} sb.append (arr[0]);//The last Word does not add a spaceSystem.out.println (Sb.tostring ());//Output    }}

Because it is a single thread, the efficiency of using StringBuilder is higher than stringbuffer, and the output is as follows:

China Hello Java Hello

Well, it's a perfect solution to the problem right now.

But in fact, it is not always separated by a space, but there are commas, periods, quotes and so on, then how to deal with it?

That can only be a character one character to judge, with Charat () to determine whether the character is a comma period or quotation marks, spaces, if you know the separation point, if not, add a temporary StringBuilder object, the code is as follows:

/** * @authorFrank * @create 2017/11/24 * @description*/ Public classTest2 { Public Static voidMain (string[] args) {String src= "Hello Java,hello China";//strings that need to be processedStringBuilder tmp =NewStringBuilder (20);//define a StringBuilder objectStringBuilder Goal =NewStringBuilder (Src.length ());//define a StringBuilder object to hold the information that is ultimately to be output        CharC//define a character variable         for(intI=src.length () -1;i>=0;i--) {C= Src.charat (i);//To take a character from a backward forward            if(c = = ' | | c = = ', ' | | c = = '. ') {//determine if the character is delimitedGoal.append (TMP);//if it is, add TMP to the goal.Goal.append (c);//Adding the separator word Fuye togetherTmp.delete (0,tmp.length ());//empty tmp}Else{Tmp.insert (0,C);//if it is not a delimited character, the word is incomplete and continues to be added to TMP            }        }        if(!tmp.equals ("") {goal.append (TMP);//If there is content in TMP, it is added to the goal} System.out.println (Goal.tostring ());//Output    }}

The output is as follows:

. China Hello,java Hello

It seems that there is no problem.

Now the difficulty is further upgraded, if there is a 20M string, "Hello_,_china_..._bye." (... Represents the middle omitted part), the word separates with the space, now needs to put all the words all reverse order, the request efficiency cannot be too low. Do not look at this 20M, it seems that there is no difficulty, the key lies in this 20M, certainly not like the first way to split with split, that will create a large array of strings, wasting a lot of space.

So here's the second way.

We first randomly generate a string, and then we use the second way to handle it:

/** * @authorFrank * @create 2017/11/24 * @description*/ Public classTest3 { Public Static voidMain (string[] args) {LongTime = 0; StringBuilder SB=NewStringBuilder (); //mister into a relatively large string         for(inti=0;i<10000000;i++) {sb.append (i+" "); } System.out.println ("String Length:" +sb.length ()); //Start calculation timeTime =System.currenttimemillis (); StringBuilder tmp=NewStringBuilder (20);//define a StringBuilder object to hold temporary dataStringBuilder Goal =NewStringBuilder (Sb.length ());//define a StringBuilder object to hold the information that is ultimately to be output        CharC//define a character variable         for(intI=sb.length () -1;i>=0;i--) {C= Sb.charat (i);//To take a character from a backward forward            if(c = = ") {//determine if the character is delimitedGoal.append (TMP);//if it is, add TMP to the goal.Goal.append (c);//Adding the separator word Fuye togetherTmp.delete (0,tmp.length ());//empty tmp}Else{Tmp.insert (0,C);//if it is not a delimited character, the word is incomplete and continues to be added to TMP            }        }        if(!tmp.equals ("") {goal.append (TMP);//If there is content in TMP, it is added to the goal} System.out.println (System.currenttimemillis ()-time);//Output Run time    }}

The output is as follows:

String length: 78888890608

608 milliseconds, the speed is OK, to generate a string or to spend a lot of time, because the memory has been copied, if the number of cycles after the addition of a 0, will be out of memory ....

Exception in thread ' main ' Java.lang.OutOfMemoryError:Java heap space at    java.util.Arrays.copyOf (Arrays.java: 3332) at    java.lang.AbstractStringBuilder.ensureCapacityInternal (Abstractstringbuilder.java: 124) at    java.lang.AbstractStringBuilder.append (abstractstringbuilder.java:448)    at Java.lang.StringBuilder.append (Stringbuilder.java:136) at    Com.frank.string.test1.Test3.main ( Test3.java:14)

At this point, the discussion of this issue is complete, if there is a better and faster way, welcome message exchange discussion.

"Java" word reverse output

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.