yf0994 / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Strings.substring with negative indices #1124

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
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.

Original issue reported on code.google.com by ddlat...@gmail.com on 28 Aug 2012 at 11:39

GoogleCodeExporter commented 9 years ago
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. =/

Original comment by wasserman.louis on 29 Aug 2012 at 12:45

GoogleCodeExporter commented 9 years ago
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.

Original comment by j...@nwsnet.de on 29 Aug 2012 at 9:35

GoogleCodeExporter commented 9 years ago

Original comment by kak@google.com on 23 Oct 2012 at 4:51

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:13

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:18

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:08