Skip to content

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.


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 < ) startIndex = s.length() + startIndex; return s.substring(startIndex); } public String slice_end(String s, int endIndex) { if (endIndex < ) endIndex = s.length() + endIndex; return s.substring(, endIndex); } public String slice_range(String s, int startIndex, int endIndex) { if (startIndex < ) startIndex = s.length() + startIndex; if (endIndex < ) endIndex = s.length() + endIndex; return s.substring(startIndex, endIndex); }
Code language: Java (java)

See also  Determine if Number is a Power of Three in Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x