0

In Java, is there a premade method that I can use to take some selected indices of an array of chars, stick the terms defined by those indices together and return it as a string? The reason I'm looking for a method here is that I would like to avoid having to create another array to hold my selected values. What I'm looking for is something that looks like this:

public String charArrayToString(char[] array, int startingIndex, int lastIndex) {
        // ignore any index that is outside of the startingIndex - lastIndex range
        // turn array[startingIndex], array[startingIndex + 1] ... array[lastIndex] into a string
}

3 Answers 3

8

I would use the constructor

public String charArrayToString(char[] array, int startingIndex, int lastIndex) {
    return new String(array, startIndex, lastIndex - startIndex + 1);
}

Depending on what you are doing with the result, a better solution might be to use StringBuilder.append

char[] coords = "000175001022".toCharArray();

StringBuilder sb = new StringBuilder();
sb.append("( ");
sb.append(coords, 0, 6);
sb.append(", ");
sb.append(coords, 6, 6);
sb.append(" )");
System.out.println(sb); // prints ( 000175, 001022 )
Sign up to request clarification or add additional context in comments.

1 Comment

I think you need a +1 here as the question appears to want to include lastIndex.
7

Sounds like you want:

return new String(array, startingIndex, lastIndex + 1 - startingIndex);

... having done some bounds checks on startingIndex and lastIndex, e.g.

startingIndex = Math.max(startingIndex, 0);
lastIndex = Math.min(lastIndex, array.length - 1);
if (startingIndex > lastIndex) {
    // Return empty string? Throw an exception?
}
return new String(array, startingIndex, lastIndex + 1 - startingIndex);

Note that if you made your upper bound exclusive instead - as most Java APIs are - you could get rid of a lot of these +1 and -1 bits.

3 Comments

The last parameter is the count, rather than the end like substring ;)
@AmitD: I prefer to validate the arguments within the methods themselves, as then you can give clearer messages. But yes.
I guess this If would be sufficient same check from new String method -if (startingIndex >= 0 && 0 <= lastIndex && lastIndex <= array.length - startingIndex) {return string} else{return error }
0
public StringBuilder append(char str[], int offset, int len) {

4 Comments

Can you add an example of how you would use this method?
This would be the best option if the OP wants to add the result to a string.
@PeterLawrey: Now who cares Jon Skeet has answered the question :)
Jon Skeet often answers questions, but you can still get some reputation. ;)

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.