google / guava

Google core libraries for Java
Apache License 2.0
50.03k stars 10.86k forks source link

Strings.substring with negative indices #1124

Open gissuebot opened 9 years ago

gissuebot commented 9 years ago

Original issue created by ddlatham on 2012-08-28 at 11:39 PM


It's often convenient to refer to string indices from the end of the string rather than the beginning. I find the following variants of String.substring helpful, especially when using a more fluent style:

public static String substring(String s, int start, int end) {
  int len = s.length();
  return s.substring(start >= 0 ? start : len + start, end >= 0 ? end : len + end);
}

public static String suffix(String s, int start)  {
  return substring(s, start, s.length());
}

Issue 503 had a broader proposal than this, but wasn't accepted as it was too lenient. This is still a strict api, but useful.

gissuebot commented 9 years ago

Original comment posted by wasserman.louis on 2012-08-29 at 12:45 AM


I know other languages have done the "negative indices count from the end of the string" thing, but I dunno if that's something I'd like to see in Java. =/

gissuebot commented 9 years ago

Original comment posted by j...@nwsnet.de on 2012-08-29 at 09:35 AM


Other languages offer negative indices support (and slicing, like Python) for collections/sequences in general. As strings are usually treated as a list of characters, that's just a specialization.

As String in Java implements CharSequence but not Collection or Iterable, this unfortunately isn't doable by, say, adding methods to Iterables and applying them to strings. :(

Then again, selecting (and not just checking against, like String.endsWith) trailing characters from a string is quite handy every now and then.

gissuebot commented 9 years ago

Original comment posted by kak@google.com on 2012-10-23 at 04:51 PM


(No comment entered for this change.)


Status: Research Labels: Package-Base