Python Splices reimplemented in Java

Python has a fantastic feature called slices. It allows you to work with a list, set or string by it’s index items.

E.g.:

string_sample = "hello world" string_sample[:-1] >>> "hello worl" string_sample[-1] >>> "d" string_sample[3] >>> "l"
Code language: Java (java)

You can also do things like:

string_sample[3:5] >>> 'lo'
Code language: Java (java)

Or even in reverse!

string_sample[::-1] >>> 'dlrow olleh'
Code language: Java (java)

A possible Java implementation

public String slice_start(String s, int startIndex) { if (startIndex < 0) startIndex = s.length() + startIndex; return s.substring(startIndex); } public String slice_end(String s, int endIndex) { if (endIndex < 0) endIndex = s.length() + endIndex; return s.substring(0, endIndex); } public String slice_range(String s, int startIndex, int endIndex) { if (startIndex < 0) startIndex = s.length() + startIndex; if (endIndex < 0) endIndex = s.length() + endIndex; return s.substring(startIndex, endIndex); }
Code language: Java (java)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments