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

6
  • 1
    What's wrong with your method? Commented Aug 1, 2016 at 16:09
  • i'm not a java guy i have to do it for a server side code thats why i dont know where to start @JornVernee Commented Aug 1, 2016 at 16:09
  • i got this api s = s.substring(0, Math.min(s.length(), 14)); for trimming the first 14 characters but how to deal with this - symbol which is combining two id's Commented Aug 1, 2016 at 16:14
  • 1
    This will help you : stackoverflow.com/questions/9276639/… Commented Aug 1, 2016 at 16:18
  • @remyboys You could skip 1 character after finding an id. Commented Aug 1, 2016 at 16:19

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
        }
    }
}

Comments

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.