0

i have a large string which contains Id's example :

HD47-4585-GG89

here at the above i have an id of a single object but sometimes it may contain id's of multiple objects like this :

HD47-4585-GG89-KO89-9089-RT45

the above haves ids of 2 objects now i want to convert the above string to an array or in multiple small Strings something like :

id1 = HD47-4585-GG89

id2 = KO89-9089-RT45

every single id haves a fixed number of characters in it here its 14 (counting the symbols too) and the number of total id's in a single String is not determined

i dont know how to do it any one can guide me with this ?

i think all i have to do is clip the first 14 characters of string then assign a variable to it and repeat this until string is empty

remy boys
  • 2,928
  • 5
  • 36
  • 65

3 Answers3

2

You could also use regex:

String input = "HD47-4585-GG89-KO89-9089-RT45";

Pattern id = Pattern.compile("(\\w{4}-\\w{4}-\\w{4})");
Matcher matcher = id.matcher(input);

List<String> ids = new ArrayList<>();

while(matcher.find()) {
    ids.add(matcher.group(1));
}

System.out.println(ids); // [HD47-4585-GG89, KO89-9089-RT45]

See Ideone.

Although this assumes that each group of characters (HD47) is 4 long.

Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93
1

Using guava Splitter

class SplitIt
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String idString = "HD47-4585-GG89-KO89-9089-RT45-HD47-4585-GG89";

        Iterable<String> result = Splitter
                .fixedLength(15)
                .trimResults(CharMatcher.inRange('-', '-'))
                .split(idString);
        String[] parts = Iterables.toArray(result, String.class);
        for (String id : parts) {
            System.out.println(id);
        }
    }
}
baao
  • 71,625
  • 17
  • 143
  • 203
1

StringTokenizer st = new StringTokenizer(String,"-");

while (st.hasMoreTokens()) {

   System.out.println(st.nextToken());

}

these tokens can be stored in some arrays and then using index you can get required data.

Madgr
  • 7
  • 4
  • [_"StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code."_](https://docs.oracle.com/javase/8/docs/api/java/util/StringTokenizer.html) – Jorn Vernee Aug 01 '16 at 16:41