How to reverse the string word by word in java when individual function is given for tokenization and reversing -


i have implemented code

import java.util.arraylist; import java.util.list;  public class client {     string data;      public string[] gettokens(string data) {          list<string> arrl=new arraylist<string>();          (string tokens : data.split(" "))         {             system.out.println(tokens);             arrl.add(tokens);         }          string[] arr;         arr=(string[]) arrl.toarray(new string[arrl.size()]);         return arr;          }      public string reverseandappend(string[] data) {          stringbuffer strbuf=new stringbuffer();         stringbuffer temp=new stringbuffer();          int i=0;         for(i=0;i<data.length;i++)         {             strbuf.append(data[i]+" ");              temp.append(strbuf.reverse().tostring());             ;         }             return temp.tostring();        }      public static void main(string[] args) {          client cl=new client();         string[] tokens=cl.gettokens("hello world");          string data=cl.reverseandappend(tokens);         system.out.println(data);      } } 

but output generated is

hello world  olleh dlrowhello  

where required output just

olleh dlrow 

what causes wrong output?

the first lines in "wrong output" generated in gettokens function: system.out.println(tokens); 3rd line have olleh dlrowhello because reverseappend function doesn't work properly.

you cand reverseappend more easier:

public string reverseandappend(string[] data) {      stringbuilder builder;      for(int i=0;i<data.length;i++)     {         builder.append(data[i].reverse());         builder.append(" ");     }     return builder.tostring(); } 

also gettokens function implemented easier well:

public string[] gettokens(string data) {          return data.split(" ");   } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -