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,847
  • 5
  • 32
  • 61

4 Answers4

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
  • 28,972
  • 3
  • 72
  • 84
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
  • 67,185
  • 15
  • 124
  • 181
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
  • 3
  • [_"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
0
String text = "HD47-4585-GG89-KO89-9089-RT45";
String first = "";
String second = "";
List<String> textList = Arrays.asList(text.split("-"));
for (int i = 0; i < textList.size() / 2; i++) {
    first += textList.get(i) + "-";
}
for (int i = textList.size() / 2; i < textList.size(); i++) {
    second += textList.get(i) + "-";
}
first = first.substring(0, first.length() - 1);
second = second.substring(0, second.length() - 1);
mate0406
  • 59
  • 1
  • 4