1

Suppose I have an int array:

intarray = [2,3,5,7,8,8,9,3...]

how to join the first 5 elements there or others?

for instance, I would have the numbers 23578 or 35788 or 57889...?

I'm trying to do it because I need to compare the numbers with each other

by the way, I'm still looking for great source that keep all docs about java language

3
  • 1
    Your documentation search can start here, if you didn't try it already. Commented Feb 14, 2013 at 11:52
  • 1
    What have you tried? Here is the current Java Documentation and the current Java Language Specification. Also, your task can be accomplished fairly easy by multiplying by 10. Commented Feb 14, 2013 at 11:53
  • I do not just know, which method a should use here, I found methods that help join arrays rather than elements into the only one array Commented Feb 14, 2013 at 11:55

4 Answers 4

2
pseudocode:

    int frstNumber = 0;
    for i = 0 to 4
         firstNumber *= 10;
         firstNumber += array[i];

    nextNumber = firstNumber
    for i = 5 to end of array
         nextNumber = (nextNumber mod 10000) * 10 + array[i]
Sign up to request clarification or add additional context in comments.

Comments

2
public static void main(String[] args) {
    int[] intarray = new int[] { 2, 3, 5, 7, 8, 8, 9, 3 };

    for (int j = 0; j < intarray.length - 4; j++) {
        String s = "";
        for (int i = j; i < j + 5; i++) {
            s = s + String.valueOf(intarray[i]);
        }
        int value = Integer.parseInt(s);
        System.out.println(value);
    }
}

Output:

23578
35788
57889
78893

5 Comments

exactly, then I would make all of the possibility variants, in your case the output data should be: 23578, 35788,57889,78893
hm, It's a bit strange, It doesn't work properly, you know. for example, if we consider a string "String ="731637176513306249192251196744265747423553491949349698352";" we'll get a 6249 number among all values
@user1813163 What you mean? We are using Array here not String.
sorry, I couldn't to insert a code in my comment correctly, I didn't get hot to insert my code in order to it will easy to read ;(
@user1813163 6249 is integer before 6 there is 0 so it prints 6249. If you want o print "06246" you can by directly print s.
1

If you want to use a library, and work at a higher level, try Guava.

    int[] ary = {7,4,1,2,5,8,9,3};
    Iterable<int[]> first5 = Iterables.limit(Lists.newArrayList(ary), 5);
    String joined = Joiner.on("").join(first5);

See Iterables.limit()

Comments

0
StringUtils.join([1, 2, 3], null) = "123"

from apache commons-lang

Comments

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.