Write a program


In this core java programming tutorial we will Write a method such that it divides whole string in strings of length 3 and reverses each string, forms its list and return it. .


Example 1 in java>
Pass string “abcdefghi” and output will be
[cba, fed, ihg]




Example 2 in java>
Pass string “abcdefgh” and output will be
[cba, fed,  hg]

Example 3 in java>
Pass string “abcdefghij” and output will be
[cba, fed, ihg,   j]



Program/ example to Write a method such that it divides whole string in strings of length 3 and reverses each string, forms its list and return it.  >
import java.util.ArrayList;
import java.util.List;
public class DividesWholeStringInStringsOfLengthOf3AndReturnListOfReversedStrings {
   static List<String> split(String s){
          List<String> list=new ArrayList<String>();//to be returned, will keep reversed subString [i.e. cba and fed and ... ]
          char ch[]=s.toCharArray();
          int ctr=0;
          char chSmall[]=new char[3];
         
          for(int i=0;i<ch.length;i++){
                 chSmall[ctr]=ch[i];
                 ctr++;
                 if(ctr==3 || i+1==ch.length){
                       ctr=0;
                       reverse(chSmall);
                       list.add(new String(chSmall));
                       chSmall=new char[3];
                 }
          }
          return list;
   }
  
   static void reverse(char ch[]){
          char temp;
          for(int i=0,j=ch.length-1;i<=ch.length/2;i++,j--){
                 temp=ch[i];
                 ch[i]=ch[j];
                 ch[j]=temp;
          }
   }
  
   public static void main(String[] args) {
          String s = "abcdefghi";
          //String s = "abcdefgh";  //Test String
          //String s = "abcdefghij"; //Test String
          List<String> list=split(s);
          System.out.println(list);
   }
}
/*OUTPUT
[cba, fed, ihg]
*/


So in this core java programming tutorial we Wrote a method such that it divides whole string in strings of length 3 and reverses each string, forms its list and return it. .


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



Related >












eEdit
Must read for you :