OneBite.Dev - Coding blog in a bite size

slice a string in java

Code snippet on how to slice a string in java

String str = "thisisastring"; 
String newStr = str.substring(4, 8);

This code takes a string, “thisisastring”, and creates a new string, “sastr”, that is a subset of the original string. The first line creates the original string and assigns it to a variable, str. The second line uses the substring() method on the str variable with two parameters. The first parameter is the starting index, which is 4, while the second parameter is one index after the end index, which is 8. The end result is that the new string, newStr, is the section of the original between the given indexes, which is “sastr” in this example.

java