0

I'm working on a small side project and need to join an array from one element to another - so if my array is: {"1","2","3","4","5"}

I would like my output to be in the form of startingElement|elementsInBetween|endingElement

my code for this section looks like this:

int lastTwo = Integer.parseInt(String.join("",numberArray[numberArray.length-2],
    numberArray[numberArray.length-1]))

This works for when I want the last two digits (in this case Strings needed to be converted to int) but I now need to join all elements except the last one.

I wrote up a solution which involved making a new array comprised of the elements of the original array minus the last element, and then using the String.join method on the new array. But I feel like this is horribly inefficient.

Edit: Here is the testing solution I came up with:

String[] test = {"a", "b", "c","d","e","f"};

    String[] test1 = new String[test.length-2];
    for(int i =0; i< test1.length; i++){
        test1[i] = test[i];
    }

as I stated, this does technically do what I want, but I feel like a cleaner solution is available...

  • Can you paste your whole solution here ? – zenwraight Dec 23 '17 at 07:50
  • You could concatenate the elements of the array to a String rather than copy them into a new array. – Code-Apprentice Dec 23 '17 at 07:56
  • I have added my test solution – Hierarchy009 Dec 23 '17 at 07:58
  • Perhaps you are asking the wrong question here. Where does your array come from? Can you change your overall implementation so that you do not need to "join an array" at all? – Code-Apprentice Dec 23 '17 at 07:58
  • In your latest code example, you could use a StringBuilder instead of an array to build up a String result. – Code-Apprentice Dec 23 '17 at 07:59
  • My array comes from a number given by the user. This number is then split up into an array of Strings (big integer style) and then manipulated depending on what I need to do. For the problem I'm encountering I need to implement code to manually check divisibility by 7, which involves taking all digits of the number minus the last one, and subtract the last number*2 – Hierarchy009 Dec 23 '17 at 08:04
  • So, you have the number 123456, and you want 12345. You can do that by dividing by 10. If you want the last digit of a number, you can do that by using the modulo operator: 12345 % 10 == 5. No need for strings and joins and parse. – JB Nizet Dec 23 '17 at 08:13
  • If you want to copy an array, just check the solution here: https://stackoverflow.com/a/5785754/3813027 – senerh Dec 23 '17 at 08:18
  • @senerh This is what I was looking for. Thank you. – Hierarchy009 Dec 23 '17 at 08:26

1 Answers1

0

Try this

StringBuffer get(String[] arr){
  StringBuffer buffer = new StringBuffer();
  for(int i = 0; i < arr.length - 2; i++) buffer.append(arr[i]);
  return buffer;
}
mehdi maick
  • 325
  • 3
  • 7