reverse each word of the String

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • moizpalitanawala
    New Member
    • Jul 2008
    • 14

    #1

    reverse each word of the String

    Hello
    I want to do reverse each word of the String
    example if input String is "Hello World" then the output should be "olleH dlroW"

    i Have tried this far
    Code:
    class g
    {
    static String s="Hello World Hello World";
    static int last=s.lastIndexOf(' ');
    static String tempS;
    
    public static void start(int count)throws Exception
    {
    if(count!=last)
    {
    tempS+=reverse(s.substring(count,s.indexOf(count+1,' ')));
    start(s.indexOf(count+1,' '));
    }
    
    if (count==last)
    {
    tempS+=reverse(s.substring(count));
    System.out.println( tempS);
    }
    }
    
    public static String reverse(String s1)
    {
    s1.trim();
    int l=s1.length();
    String temp=null;
    for(int i=l;i>0;i++)
    {
    temp+=s1.charAt(i);
    }
    temp+=" ";
    return temp;
    }
    
    public static void main()throws Exception
    {
    start(0);
    }
    }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Have a look at the StringBuilder class; it can do the work for you.

    kind regards,

    Jos

    Comment

    • jkmyoung
      Recognized Expert Top Contributor
      • Mar 2006
      • 2057

      #3
      Line 26. String temp=null;
      This should be String temp = new String(); //empty string

      You can't add characters to a null, but you can add them to an empty string.

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by jkmyoung
        Line 26. String temp=null;
        This should be String temp = new String(); //empty string

        You can't add characters to a null, but you can add them to an empty string.
        This works for me:

        Code:
        public class AddToNull {
        
        	public static void main (String[] args) {
        
        		String s= null+"abc";
        		System.out.println(s);
        	}
        }
        kind regards,

        Jos ;-)

        Comment

        Working...