bayard 02/02/13 21:03:31
Modified: util/src/java/org/apache/commons/util StringUtils.java
Log:
Made StringUtils.substring far more lenient than java.lang.String.substring.
It won't complain if too high an end value is used and it allows negative
values to be used. Negative meaning distance from the end of the string.
It also won't complain if too low a negative value is used.
One question standing is what to do if the start index is higher than the end index.
Should it reverse the text when it returns it, return a wrap around,
complain, or silently flip the two numbers.
Revision Changes Path
1.25 +46 -7
jakarta-commons-sandbox/util/src/java/org/apache/commons/util/StringUtils.java
Index: StringUtils.java
===================================================================
RCS file:
/home/cvs/jakarta-commons-sandbox/util/src/java/org/apache/commons/util/StringUtils.java,v
retrieving revision 1.24
retrieving revision 1.25
diff -u -r1.24 -r1.25
--- StringUtils.java 4 Feb 2002 17:13:07 -0000 1.24
+++ StringUtils.java 14 Feb 2002 05:03:31 -0000 1.25
@@ -85,7 +85,7 @@
* @author <a href="mailto:[EMAIL PROTECTED]">Greg Coladonato</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Bayard</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Ed Korthof</a>
- * @version $Id: StringUtils.java,v 1.24 2002/02/04 17:13:07 bayard Exp $
+ * @version $Id: StringUtils.java,v 1.25 2002/02/14 05:03:31 bayard Exp $
*/
public class StringUtils
{
@@ -1633,21 +1633,60 @@
}
static public String substring(String str, String start) {
- return substring(str, start, "-1");
+ return substring(str, NumberUtils.stringToInt(start));
}
static public String substring(String str, int start) {
- return substring(str, start, -1);
+ if(str == null) {
+ return null;
+ }
+
+ // handle negatives
+ if(start < 0) {
+ start = str.length() + start; // remember start is negative
+ }
+
+ if(start < 0) {
+ start = 0;
+ }
+
+ return str.substring(start);
}
static public String substring(String str, String start, String end) {
return substring(str, NumberUtils.stringToInt(start),
NumberUtils.stringToInt(end));
}
static public String substring(String str, int start, int end) {
- if(end == -1) {
- return str.substring(start);
- } else {
- return str.substring(start, end);
+ if(str == null) {
+ return null;
+ }
+
+ // handle negatives
+ if(end < 0) {
+ end = str.length() + end; // remember end is negative
+ }
+ if(start < 0) {
+ start = str.length() + start; // remember start is negative
+ }
+
+ // check length next
+ if(end > str.length()) {
+ // check this works.
+ end = str.length();
}
+
+ // what if start is greater than end??
+
+ if(start < 0) {
+ start = 0;
+ }
+
+ // a good default?
+ if(end < 0) {
+ end = 0;
+ }
+
+ return str.substring(start, end);
}
+
static public String random(int count) {
return random(count, false, false);
--
To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>