Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Five Ways to Reverse a String of Words (C#, Perl 5, Perl 6, Ruby, Haskell) (a Java 1.5 version)

by IulianU (Initiate)
on Dec 14, 2006 at 22:08 UTC ( #589920=note: print w/ replies, xml ) Need Help??


in reply to Five Ways to Reverse a String of Words (C#, Perl 5, Perl 6, Ruby, Haskell)

public static String reverseWords( String src ) { List<String> pcs = Arrays.asList( src.split("\\s+") ); Collections.reverse( pcs ); StringBuffer result = new StringBuffer(); for( String pc : pcs ) result.append(" ").append(pc); return result.substring(1); }


Comment on Re: Five Ways to Reverse a String of Words (C#, Perl 5, Perl 6, Ruby, Haskell) (a Java 1.5 version)
Download Code
Re^2: Five Ways to Reverse a String of Words (C#, Perl 5, Perl 6, Ruby, Haskell) (a Java 1.5 version)
by IulianU (Initiate) on Dec 14, 2006 at 22:39 UTC
    Of course the above is broken :) It appends a trailing empty space. There are two ways to fix it: 1) return result.toString().trim(); instead of return result.substring(1); 2) filter out zero-length pieces in the for loop with something like if( pc.length() == 0 )

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://589920]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2015-07-07 02:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (86 votes), past polls