Skip to content

Commit da14b5f

Browse files
committed
Add Strings.substring() that handles short strings.
1 parent 2345e11 commit da14b5f

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

src/main/java/org/elasticsearch/common/Strings.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1548,4 +1548,21 @@ public static String randomBase64UUID(Random random) {
15481548
throw new ElasticsearchIllegalStateException("should not be thrown");
15491549
}
15501550
}
1551+
1552+
/**
1553+
* Return substring(beginIndex, endIndex) that is impervious to string length.
1554+
*/
1555+
public static String substring(String s, int beginIndex, int endIndex) {
1556+
if (s == null) {
1557+
return s;
1558+
}
1559+
1560+
int realEndIndex = s.length() > 0 ? s.length() - 1 : 0;
1561+
1562+
if (endIndex > realEndIndex) {
1563+
return s.substring(beginIndex);
1564+
} else {
1565+
return s.substring(beginIndex, endIndex);
1566+
}
1567+
}
15511568
}

0 commit comments

Comments
 (0)