bula
bula

Reputation: 9439

implementation for java substring with negative values

in java,

String month= "November 2014";

for making a substring giving the index from right hand side, I cannot use

someString.substring(-4);

as negative values are not supported.

Is there any simple implementation I can use to achieve this.

Upvotes: 1

Views: 3100

Answers (2)

M A
M A

Reputation: 72884

No, negative numbers are not allowed (it would throw a StringIndexOutOfBoundsException). You can use this:

if(month.length() >= 4) {
    year = month.substring(month.length() - 4);
}

Upvotes: 5

user6371268
user6371268

Reputation:

I love Python's indexing and prefer to be able to use it in Java as well ;)

A general implementation of substring with support for negative indexing could be implemented like this:

A method for converting negative indexes to their positive equivalent is useful:

private static int toPosIndex(String str, int index) {
    if (index >= 0) return index;
    else return str.length() + index;

This method can then be used to declare a substring method with support for negative indexes:

public static String negSubstring(String str, int index1, int index2) {
    return str.substring(toPosIndex(str, index1), toPosIndex(str, index2));
}

and if needed an equivalent to the version of substring with only one index parameter:

public static String negSubstring(String str, int index) {
    return str.substring(toPosIndex(str, index));
}

(I realise the question is more than two years old, but figured that other new users might be interested in a general answer to the question).

Upvotes: 1

Related Questions