From da14b5f5e41bdd08fd9dfab3ea42ea4778ed0bc1 Mon Sep 17 00:00:00 2001 From: Andrew Raines Date: Tue, 7 Jan 2014 13:54:20 -0600 Subject: [PATCH] Add Strings.substring() that handles short strings. --- .../java/org/elasticsearch/common/Strings.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main/java/org/elasticsearch/common/Strings.java b/src/main/java/org/elasticsearch/common/Strings.java index 196f300613c..aa85afa294d 100644 --- a/src/main/java/org/elasticsearch/common/Strings.java +++ b/src/main/java/org/elasticsearch/common/Strings.java @@ -1548,4 +1548,21 @@ public class Strings { throw new ElasticsearchIllegalStateException("should not be thrown"); } } + + /** + * Return substring(beginIndex, endIndex) that is impervious to string length. + */ + public static String substring(String s, int beginIndex, int endIndex) { + if (s == null) { + return s; + } + + int realEndIndex = s.length() > 0 ? s.length() - 1 : 0; + + if (endIndex > realEndIndex) { + return s.substring(beginIndex); + } else { + return s.substring(beginIndex, endIndex); + } + } }