Android Textutils.split для доставки строки фиксированной длины []

StackOverflow https://stackoverflow.com/questions/5059639

Вопрос

Я не могу получить строку, сломанную на фиксированные куски длины и добавляю в ArrayList ... Код ниже, как и ожидалось, но все MessageTosplit [] до последнего - NULL.Последний на самом деле имеет значение в нем.

В примере ниже, если текст редактирования возвращается, «01234567890», то «», «» и «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 split operation, the regex pattern is the separator. For example, if the regex pattern were ;, then 12;34;56 would be split into 12, 34, and 56.

So in your case 01234567890 is split into "" (the string before 0123), "" (the string between 0123 and 4567) and 890 (the remainder of the string after 4567).

You probably don't want to use split but rather something like this:

Pattern p = Pattern.compile(".{1,4}");
Matcher regexMatcher = p.matcher(messageToSplit);
while (regexMatcher.find()) {
    myText.add(regexMatcher.group());
} 

.{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).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top