-4

I have a string like "#123#456 #abc". my requirement is dividing the string into tokens based on the #. So my result tokens are #123,#456,#abc.

How to divide the string in android?

Rajesh
  • 521
  • 5
  • 19

5 Answers5

1

Just use string split method then add # to the start

panda
  • 456
  • 4
  • 12
1

This should help you

   String str = "#123#456#abc";
   String[] arr = str.split("#");

    for(int i=1;i< arr.length;i++){
     System.out.println("#" + arr[i]);
    }

Output

#123
#456
#abc
Sathish Kumar J
  • 4,280
  • 1
  • 20
  • 48
1

You will need to split your String with regex "#". I wrote an example for your case.

    final String entry = "#123#456#abc";
    String[] tokens = entry.split("#");
    // Your tokens array will contain {"", "123", "456", "abc"}

    // Filter out the empty values and add an '#' before the others
    List<String> formattedTokens = new ArrayList<>();
    for (String token : tokens) {
        if(token.length() > 0){
            formattedTokens.add(String.format("#%s", token));
        }
    }

    // Your formattedTokens list will contain {"#123", "#456", "#abc"}
MrJM
  • 1,214
  • 1
  • 12
  • 26
0

use String.split(#) for splitting the string into string[] and then append # to each string after that

JAAD
  • 12,349
  • 7
  • 36
  • 57
0

see Rege for more info - you can set regular expression and parse String as you want

Alex Shutov
  • 3,217
  • 2
  • 13
  • 11