1

I have the array : ['a','b','c','d']

I want to take a certain range of the array, say [0,2] and make this a string. The result would be "abc".

This solution actually works :

private static String convertPartArrayToString(char[] array, int startIndex, int endIndex) {
    char[] dest = new char[endIndex - startIndex + 1];
    System.arraycopy( array, startIndex, dest, 0, endIndex - startIndex + 1 );
    return new String(dest);
}

But isn't there a way to make this faster than to copy the array?

IEatBagels
  • 823
  • 2
  • 8
  • 23

2 Answers2

2

String has a constructor that takes an array of char, a start and count.

The array will still be (defensively) copied as otherwise mutable state will escape and you will no longer have an immutable String.

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81
  • The reason I didn't use that is because I didn't know it existed! :p – IEatBagels Nov 19 '15 at 15:19
  • 1
    Word of warning - The ctor (and the methods suggested by Jordi Castilla use an offset and a count, not a "to-from" as you use in your example. Not a large problem, but one to be aware off. You will always have a defensive copy as otherwise the state will escape and the string will no longer be mutable. It comes down to which reads better. I'd use the ctor as I'm constructing a string. But that me. – Michael Lloyd Lee mlk Nov 19 '15 at 15:27
1

You have plenty of JAVA built in methods, in this case you are using System API, wich is not really usual in this cases, instead of this you can use:

Arrays API:

private static String convertPartArrayToString(char[] array, int from, int to) {  
    return Arrays.toString(Arrays.copyRange(array, from, to);
}

String API

private static String convertPartArrayToString(char[] array, int from, int to) {  
    return String.copyValueOf(array, from, to - from);
}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109