I cannot get a string broken into fixed length chunks and added to an ArrayList … the code below iterates through as expected, but all the messageToSplit[] upto the last one are null. The last one actually has a value in it.
In the example below if the edit text returned, “01234567890” then “”, “” and “890”.
Pattern p = Pattern.compile(".{4}");
ArrayList<String> myText = new ArrayList<String>();
String[] messageToSplit = TextUtils.split(myStringEditText.getText().toString(), p);
int x = 0;
while(x <= (myStringEditText.getText().toString().length() / 4)) {
Toast.makeText(getBaseContext(), x+": '" + messageToSplit[x] + "'", Toast.LENGTH_SHORT).show();
myText.add(messageToSplit[x]);
x++;
}
In a
splitoperation, the regex pattern is the separator. For example, if the regex pattern were;, then12;34;56would be split into12,34, and56.So in your case
01234567890is split into""(the string before0123),""(the string between0123and4567) and890(the remainder of the string after4567).You probably don’t want to use
splitbut rather something like this:.{1,4}will match 4 characters if it can, but make do with 1-3 if four are no longer available (which might happen at the end of the string if its length is not a multiple of 4).