Write a method such that it divides whole string in strings of length 3, forms its list and return it in java


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


Example 1 in java>
Pass string “abcdefghi” and output will be
abc
def
ghi



Example 2 in java>
Pass string “abcdefgh” and output will be
abc
def
gh

Example 3 in java>
Pass string “abcdefghij” and output will be
abc
def
ghi
j


Program/ example to Write a method such that it divides whole string in strings of length 3, forms its list and return it in java >
import java.util.*;
public class DividesWholeStringInStringsOfLengthOf3AndReturnList {
   List<String> methodDividesStringAndReturnList(int n) {
          String s = "abcdefghi";
          //String s = "abcdefgh"; //Test String
          //String s = "abcdefghij"; //Test String
          char ch[] = s.toCharArray();
          int ctr = 0;
          List<String> l = new ArrayList<String>();
          String temp = "";
          for (int i = 0; i < ch.length; i++) {
                 if (ctr < n) {
                       temp += String.valueOf(ch[i]);
                       ctr++;
                 }
                 if (ctr == n || i == ch.length - 1) {
                       l.add(temp);
                       temp = "";
                       ctr = 0;
                 }
          }
          return l;
   }
   public static void main(String[] args) {
          DividesWholeStringInStringsOfLengthOf3AndReturnList o = new DividesWholeStringInStringsOfLengthOf3AndReturnList();
          List<String> l = o.methodDividesStringAndReturnList(3);
          // Display list
          Iterator<String> it = l.iterator();
          while (it.hasNext()) {
                 System.out.println(it.next());
          }
   }
}
/*OUTPUT
abc
def
ghi
*/



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



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 >




No comments:

Post a Comment