0

I need to Split my string into some specified length(10 char).

Below is my code:

Pattern p = Pattern.compile(".{0,10}");
Matcher m = p.matcher("012345678901234567890123456");
List<String> emailStr = new ArrayList<String>();
while(m.find())
{
   System.out.println(m.group());
}

As for my requirment I will get max of 3 Strings. I want to assign this "n" number of strings to separate variable. I donot have any idea on this. Please help on it.

Srinivasan
  • 11,718
  • 30
  • 64
  • 92

2 Answers2

0

You can use this do get what you want:

public static String[] splitter(String str, int len) {
    String[] array = new String[(int) str.length() / len + 1];
    for (int i = 0; i < str.length() / len + 1; i++) {
        String s = "";
        for (int j = 0; j < len; j++) {
            int index = i * len + j;
            if (index < str.length())
                s += str.charAt(i * len + j);
            else
                break;
        }
        array[i] = s;
    }
    return array;
}
jrad
  • 3,172
  • 3
  • 22
  • 24
0

Building on the answer Jack gave:

public List<String> splitter(String str, int len) {
  ArrayList<String> lst = new ArrayList<String>((str.length() - 1)/len + 1);
  for (int i = 0; i < str.length(); i += len)
    lst.add(str.substring(i, Math.min(str.length(), i + len)));
  return lst;
}

Don't use a Pattern Matcher for this. Don't use regular expressions where they are not needed, in languages where regular expressions are not a fundamental concept. In , you do everything you can using regular expressions, but otherwise don't.

Community
  • 1
  • 1
MvG
  • 57,380
  • 22
  • 148
  • 276