Python Splices reimplemented in Java

0 min read 128 words

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"

You can also do things like:

string_sample[3:5]
>>> 'lo'

Or even in reverse!

string_sample[::-1]
>>> 'dlrow olleh'

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);
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags