Stephen Muga
Stephen Muga

Reputation: 183

Extract groups of characters in a string

I have a string 123456789
I also have a bunch of numbers (identities, if you will) such as

2 1 1 1 2 2
2 1 1 1 3 1
2 1 1 2 1 2
2 1 1 2 2 1
2 1 1 3 1 1

The idea is, these numbers specify the groups of digits that should be extracted from the string (left to right order, if that matters). Therefore, a number like 2 3 2 1 1 means Output the first 2 characters, then the next 3 characters, then the next 2 characters, then the next 1 character, then finally the last 1 character remaining.So as examples,

2 1 1 1 2 2 should output 12 3 4 5 67 89
2 1 1 1 3 1 should output 12 3 4 5 678 9
2 1 1 2 1 2 should output 12 3 4 56 7 89
2 1 1 2 2 1 should output 12 3 4 56 78 9
2 1 1 3 1 1 should output 12 3 4 567 8 9

I tried working with the method charAt() but it would seem that's just not for me

public static void main(String[] args) {
    String mine = "123456789";
    System.out.println(mine.charAt(2)+"\t"+mine.charAt(1)+"\t"+
    mine.charAt(1)+"\t"+mine.charAt(1)+"\t"+mine.charAt(2)
    +"\t"+mine.charAt(2));
}

The above gives an unwanted output

3   2   2   2   3   3

How do I solve this rather tricky (for me) issue ?

Upvotes: 0

Views: 97

Answers (2)

garykwwong
garykwwong

Reputation: 2427

I've given a simple trial on it. Does below give you some help?

public static void main(String[] args) {

    int[][] identitiesBunch = new int[][] { 
        {2, 1, 1, 1, 2, 2},
        {2, 1, 1, 1, 3, 1},
        {2, 1, 1, 2, 1, 2},
        {2, 1, 1, 2, 2, 1},
        {2, 1, 1, 3, 1, 1} 
    };

    String mine = "123456789";
    char[] numbers = mine.toCharArray();

    int index = 0;
    for (int[] identities: identitiesBunch) {
        for (int id: identities ) {
            for (int i = 0 ; i < id; i++)
                System.out.print(numbers[index++]);
            System.out.print(' ');
        }
        index = 0;
        System.out.println();
    }
}

Upvotes: 0

Reger05
Reger05

Reputation: 223

This should do the work for you.

    public static void main(String[] args){
        String identities = "2 1 1 1 3 1";

        String stringToBreakApart = "123456789";

        StringBuilder sb = new StringBuilder();

        int currentPosition = 0;

        for(String identityString : identities.split(" ")){
            int identity = Integer.parseInt(identityString);

            sb.append(stringToBreakApart, currentPosition, currentPosition += identity);
            sb.append(" ");

        }

        System.out.println(sb.toString());
    }

Upvotes: 1

Related Questions