You can use String#split:

String s = "14.015_AUDI";
String[] parts = s.split("_"); //returns an array with the 2 parts
String firstPart = parts[0]; //14.015

You should add error checking (that the size of the array is as expected for example)

Answer from assylias on Stack Overflow
🌐
Coding Champ
coding-champ.com › tutorials › java › string-slicing
Java - String Slicing
In this example, 1 skips the first character - c. str.length() - 1 is the same as 8 - 1 which is 7. So it take the rest of the string until the symbol at the 7th index is reached - r.
🌐
AlgoCademy
algocademy.com › link
String Slicing in Java | AlgoCademy
You can see in our example that the character at index 2 (v) was included while the character at index 6 (r) was excluded. Also notice that language preserved its value. The slicing does not affect the original string. It just creates a brand new one representing the sliced substring. If you omit the endIndex, the slice() extracts to the end of the string: String language = "JavaScript"; String substring = language.substring(4); System.out.println(substring); // Output: "Script"
Discussions

How to slice a string based on the Nth occurrence of a certain character
You want String.split(). public static void main(String[] args) { String s = "test1.test2.test3.test4"; // First parameter is the delimiter, second parameter is the size of the array that you want returned. String splitString = s.split("\\." , 2); //The last string in this array will be the one that you want. String myString = splitString[splitString.length-1]; System.out.println(myString); } The output is: test2.test3.test4 In your case, if you want everything AFTER the n th period, then the size of your array would need to be 1 higher than n. So if you wanted everything after the 2nd period, you would use: s.split("\\." , 3); Again, you would still want the last String in the array, since the array that's returned would be: ["test1" , "test2" , "test3.test4"] More on reddit.com
🌐 r/learnjava
4
2
September 27, 2016
Slice string in java - Stack Overflow
How slice string in java? I'm getting row's from csv, and xls, and there for example data in cell is like 14.015_AUDI How can i say java that it must look only on part before _ ? So after manipu... More on stackoverflow.com
🌐 stackoverflow.com
Is there a Java equivalent to Python's Easy String Splicing? - Stack Overflow
Java doesn't support operator overloading so there's no way to give that functionality to the language. Using substring isn't so bad. You shouldn't have to do it too often. You could always write helper functions if you're doing it very often to simplify your usage. ... -1: The OP is talking about negative slice indices, not... whatever it is you're on about. They certainly aren't trying to modify strings in-place going by ... More on stackoverflow.com
🌐 stackoverflow.com
How do I split a string in Java? - Stack Overflow
I want to split a string using a delimiter, for example split "004-034556" into two separate strings by the delimiter "-": part1 = "004"; part2 = "034556"; ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Sentry
sentry.io › sentry answers › java › how to split a string in java
How to split a string in Java | Sentry
how to split a string in java · In the example above, we use : as the delimiter, but note that the parameter the split() method takes is a regular expression. This means it is easy to do things like split on one or more : characters by using ...
🌐
Baeldung
baeldung.com › home › java › java string › java equivalent to python’s easy string slicing
Java Equivalent to Python’s Easy String Slicing | Baeldung
March 25, 2025 - We use a loop to extract characters while handling indices correctly. In this article, we saw that although Java lacks Python’s concise string-slicing syntax, we can achieve similar functionality using substring(), loops, and StringBuilder. By leveraging these techniques, Java developers ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-split-a-string-by-character
Java - Split a String by Character - GeeksforGeeks
July 23, 2025 - In Java, we can use the split() method from the String class to split a string by character, which simplifies this process by taking a regular expression (regex) as its argument.
Find elsewhere
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Java String Slicing Example - Java Code Geeks
March 21, 2025 - For example, extracting every second character in reverse results in “Wlo”. The following output is produced when the code is executed: Basic Slicing: Hello World Negative Indexing: World! Step Slicing: Hlo ol! Reversed String: !dlroW ,olleH Negative Step Slicing: lo o · Python makes string slicing easy with its start:stop:step notation, while Java requires substring() and loops for similar functionality. By implementing custom methods, we can achieve similar results in Java.
🌐
CodingTechRoom
codingtechroom.com › question › slice-string-java
How to Slice a String in Java: A Comprehensive Guide - CodingTechRoom
String text = "Programming in Java"; String slice1 = text.substring(0, 11); // Extracts "Programming" String slice2 = text.substring(11); // Extracts " in Java" Understanding the positions of characters in strings can be tricky, especially for newcomers to Java.
Top answer
1 of 8
25

Sorry, Java's substring is not as flexible as Python's slice notation.

In particular:

  • You can give it just a begin, or a begin and end, but not just an end. (Also, no step, but you don't miss that as much.)
  • Negative indices are an error, not a count from the end.

You can see the docs here.

However, it's not hard at all to write this on your own:

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);
}

Put those as static methods of some utility class.

Obviously this isn't exactly the same as Python, but it probably handles all the cases you want, and very simple. If you want to handle other edge cases (including things like step and passing slices around and so on), you can add whatever additional code you want; none of it is particularly tricky.


Other sequences are basically the same, but there you're going to want subSequence instead of substring. (You can also use subSequence on strings, because a String is a CharSequence.)

Arrays aren't actually a type of sequence at all; you'll need to write code that explicitly creates a new Array and copies the sub-array. But it's still not much more complicated.


Note that you may want to look for a library that's already done this for you. There are at least three linked in other answers on this page, which should make your search easy. :) (You may still want to do it for yourself once, just to understand how those libraries work—but for production code, I'd rather use a library where someone else has figured out and tested all of the edge cases than to reimplement the wheel and deal with them as they get caught in unit tests, or errors in the field…)

2 of 8
11

Java Boon Slice Notation allows all of that and with Strings, Lists, Sets, Maps, etc.

Many languages have slice notation (Ruby, Groovy and Python). Boon adds this to Java.

Boon has three slc operators: slc, slc (start only), and slcEnd.

With Boon you can slice strings, arrays (primitive and generic), lists, sets, tree sets, tree map's and more.

Slice notations - a gentle introduction

The boon slice operators works like Python/Ruby slice notation:

Ruby slice notation

 arr = [1, 2, 3, 4, 5, 6]
 arr[2]    #=> 3
 arr[-3]   #=> 4
 arr[2, 3] #=> [3, 4, 5]
 arr[1..4] #=> [2, 3, 4, 5]

Python slice notation

string = "foo bar" 
string [0:3]  #'foo'
string [-3:7] #'bar'

What follows is derived from an excellent write up on Python's slice notation:

The basics of slice notations are as follows:

Python Slice Notation

     a[ index ]       # index of item
     a[ start : end ] # items start through end-1
     a[ start : ]     # items start through the rest of the array
     a[ : end ]       # items from the beginning through end-1
     a[ : ]           # a copy of the whole array

Java Slice Notation using Boon:

      idx( index )         // index of item
      slc( a, start, end ) // items start through end-1
      slc( a, start )      // items start through the rest of the array
      slcEnd( a, end )     // items from the beginning through end-1
      copy( a )            // a copy of the whole array

slc stands for slice idx stands for index slcEnd stands for end slice. copy stands for well, err, um copy of course

The key point to remember is that the end value represents the first value that is not in the selected slice. So, the difference between end and start is the number of elements selected. The other feature is that start or end may be a negative number, which means it counts from the end of the array instead of the beginning.

Thus:

Python slice notation with negative index

         a[ -1 ]    # last item in the array
         a[ -2: ]   # last two items in the array
         a[ :-2 ]   # everything except the last two items

Java negative index

         idx   ( a, -1)     // last item in the array
         slc   ( -2 )       // last two items in the array
         slcEnd( -2 )       // everything except the last two items

Python and Boon are kind to the programmer if there are fewer items than you ask for: Python does not allow you to go out of bounds, if you do it returns at worse an empty list. Boon follows this tradition, but provides an option to get exception for out of bounds (described later). In Python and Boon, if you go to far, you get the length, if you try to go under 0 you get 0 (under 0 after calculation). Conversely, Ruby gives you a null pointer (Nil). Boon copies Python style as one of the goals of Boon is to avoid ever returning null (you get an exception, Option). (Boon has second operator called zlc which throws an out of bounds index exception, but most people should use slc.)

For example, if you ask for slcEnd(a, -2) (a[:-2]) and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, and with Boon you have that option.

More slicing

Here are some basic Java types, list, array, veggies, primitive char array, and a primitive byte array.

Declare variables to work with in Boon

//Boon works with lists, arrays, sets, maps, sorted maps, etc.
List<String> fruitList;
String [] fruitArray;
Set<String> veggiesSet;
char [] letters;
byte [] bytes;
NavigableMap <Integer, String> favoritesMap;
Map<String, Integer> map;

//In Java a TreeMap is a SortedMap and a NavigableMap by the way.

Boon comes with helper methods that allow you to easily create lists, sets, maps, concurrent maps, sorted maps, sorted sets, etc. The helper methods are safeList, list, set, sortedSet, safeSet, safeSortedSet, etc. The idea is to make Java feel more like list and maps are built in types.

Initialize set, list, array of strings, array of chars, and array of bytes

veggiesSet  =  set( "salad", "broccoli", "spinach");
fruitList   =  list( "apple", "oranges", "pineapple");
fruitArray  =  array( "apple", "oranges", "pineapple");
letters     =  array( 'a', 'b', 'c');
bytes       =  array( new byte[]{0x1, 0x2, 0x3, 0x4});

There are even methods to create maps and sorted maps called map, sortedMap, safeMap (concurrent) and sortedSafeMap(concurrent). These were mainly created because Java does not have literals for lists, maps, etc.

Java: Use map operator to generate a SortedMap and a Map

 favoritesMap = sortedMap(
      2, "pineapple",
      1, "oranges",
      3, "apple"
 );


 map =    map (
    "pineapple",  2,
    "oranges",    1,
    "apple",      3
 );

You can index maps, lists, arrays, etc. using the idx operator.

Java: Using the Boon Java idx operator to get the values at an index

 //Using idx to access a value.

 assert idx( veggiesSet, "b").equals("broccoli");

 assert idx( fruitList, 1 ).equals("oranges");

 assert idx( fruitArray, 1 ).equals("oranges");

 assert idx( letters, 1 ) == 'b';

 assert idx( bytes, 1 )      == 0x2;

 assert idx( favoritesMap, 2 ).equals("pineapple");

 assert idx( map, "pineapple" )  == 2;

The idx operators works with negative indexes as well.

Java: Using idx operator with negative values

         //Negative indexes

          assert idx( fruitList, -2 ).equals("oranges");

          assert idx( fruitArray, -2 ).equals("oranges");

          assert idx( letters, -2 ) == 'b';

          assert idx( bytes, -3 )   == 0x2;

Ruby, Groovy and Python have this feature. Now you can use this in Java as well! The Java version (Boon) works with primitive arrays so you get no auto-boxing.

Something that Ruby and Python don't have is slice notation for SortedSets and SortedMaps. You can use slice notation to search sorted maps and sorted sets in Java

Slice notations works with sorted maps and sorted sets.

Here is an example that puts a few concepts together.

          set = sortedSet("apple", "kiwi", "oranges", "pears", "pineapple")

          slcEnd( set, "o" )      //returns ("oranges", "pears", "pineapple")
          slc( set, "ap", "o" )   //returns ("apple", "kiwi"),
          slc( set, "o" )         //returns ("apple", "kiwi")

You are really doing with slicing of sorted maps and sorted sets is a between query of sorts. What item comes after "pi"?

          after(set, "pi") //pineapple

And before pineapple?

          before(set, "pi")

Ok, let go through it step by step....

  NavigableSet<String> set =
          sortedSet("apple", "kiwi", "oranges", "pears", "pineapple");

  assertEquals(

          "oranges", idx(set, "ora")

  );

Remember: TreeSet implements NavigableSet and SortedSet.

This was derived from my blog....

http://rick-hightower.blogspot.com/2013/10/java-slice-notation-to-split-up-strings.html

More examples are there.

I derived some of the verbiage from this discussion on Python slicing.

Explain Python's slice notation

Here is the Boon project link:

https://github.com/RichardHightower/boon

Now let's continue to SLICE!

We can look up the first fruit in the set that starts with 'o' using:

idx(set, "o")

Here is is with the set of fruit we created earlier (set is a TreeSet with "apple", "kiwi", "oranges", "pears", "pineapple" in it).

      assertEquals(

          "oranges", idx(set, "o")

      );

We found oranges!

Here it is again but this time we are searching for fruits that start with "p", i.e., idx(set, "p").

      assertEquals(
          "pears",
          idx(set, "p")
      );

Yeah! We found pears!

How about fruits that start with a "pi" like "pineapple" - idx(set, "pi")

  assertEquals(
          "pineapple",
          idx(set, "pi")
  );

You could also ask for the item that is after another item. What is after "pi"? after(set, "pi")

  assertEquals(

          "pineapple",
          after(set, "pi")

  );

The "pineapple" is after the item "pi". after and idx are the same by the way. So why did I add an after? So I can have a before!!! :) What if you want to know what is before "pi"?

before(set, "pi")

 
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-string-substring
Master Java Substring Method: Examples, Syntax, and Use Cases | DigitalOcean
Learn how to use the Java substring method. Explore syntax, practical examples, and common errors to handle substrings effectively.
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-string-substring-method-example
Java String substring() Method with examples
Here we have a string and we want to get a substring between two strings “Beginners” and “com”. To do this, we have searched the index of first string using indexOf() and added the length of this string, this is because indexOf() gives the index of first character of the string but we want to start reading after the end of string “Beginners”. Similarly, we found the starting index of second string “com” and get the substring between these indexes using substring method. public class JavaExample{ public static void main(String[] args){ //input string String str = "Welcome to [BeginnersBook.com]"; //get the substring between "Beginners" and "com" int start = str.indexOf("Beginners")+"Beginners".length(); int end = str.lastIndexOf("com"); String outStr = str.substring(start, end); System.out.println(outStr); } }
🌐
javaspring
javaspring.net › blog › java-slice-string
Mastering String Slicing in Java — javaspring.net
The substring method is the most straightforward way to slice a string in Java. It is a method of the String class and has two overloaded forms: public class SubstringExample { public static void main(String[] args) { String original = "Hello, ...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › String.html
String (Java Platform SE 8 )
July 21, 2026 - The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class. The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings.
🌐
Baeldung
baeldung.com › home › java › java string › how to truncate a string in java
How to Truncate a String in Java | Baeldung
January 8, 2024 - Thus, the character at the index length will not be included in the returned substring. Another way to truncate a String is to use the split() method, which uses a regular expression to split the String into pieces.
🌐
Baeldung
baeldung.com › home › java › java string › get substring from string in java
Get Substring from String in Java | Baeldung
July 21, 2024 - For more details on the Java regular expressions check out this tutorial. We can use the split method from the String class to extract a substring. Say we want to extract the first sentence from the example String.
🌐
IONOS
ionos.com › digital guide › websites › web development › java substrings
How to use the Java substring method - IONOS
January 6, 2025 - To use substring(), you’ll first enter the string that you want to extract the substring from. Then you use an integer to define where the substring should begin. You can view the output with the Java command System.out.println. The method works in­clu­sive­ly, meaning that the character that is in the position of the index you enter will also be separated.
Top answer
1 of 16
3416

Use the appropriately named method String#split().

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Note that split's argument is assumed to be a regular expression, so remember to escape special characters if necessary.

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

For instance, to split on a period/dot . (which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).

String[] parts = string.split(Pattern.quote(".")); // Split on the exact string.

To test beforehand if the string contains certain character(s), just use String#contains().

if (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");
}

Note, this does not take a regular expression. For that, use String#matches() instead.

If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.

String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42
2 of 16
91

An alternative to processing the string directly would be to use a regular expression with capturing groups. This has the advantage that it makes it straightforward to imply more sophisticated constraints on the input. For example, the following splits the string into two parts, and ensures that both consist only of digits:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

class SplitExample
{
    private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");

    public static void checkString(String s)
    {
        Matcher m = twopart.matcher(s);
        if (m.matches()) {
            System.out.println(s + " matches; first part is " + m.group(1) +
                               ", second part is " + m.group(2) + ".");
        } else {
            System.out.println(s + " does not match.");
        }
    }

    public static void main(String[] args) {
        checkString("123-4567");
        checkString("foo-bar");
        checkString("123-");
        checkString("-4567");
        checkString("123-4567-890");
    }
}

As the pattern is fixed in this instance, it can be compiled in advance and stored as a static member (initialised at class load time in the example). The regular expression is:

(\d+)-(\d+)

The parentheses denote the capturing groups; the string that matched that part of the regexp can be accessed by the Match.group() method, as shown. The \d matches and single decimal digit, and the + means "match one or more of the previous expression). The - has no special meaning, so just matches that character in the input. Note that you need to double-escape the backslashes when writing this as a Java string. Some other examples:

([A-Z]+)-([A-Z]+)          // Each part consists of only capital letters 
([^-]+)-([^-]+)            // Each part consists of characters other than -
([A-Z]{2})-(\d+)           // The first part is exactly two capital letters,
                           // the second consists of digits
🌐
Programiz
programiz.com › java-programming › library › string › substring
Java String substring()
System.out.println(str1.substring(0)); // program // 4th character to the last character System.out.println(str1.substring(3)); // gram } } class Main { public static void main(String[] args) { String str1 = "program"; // 1st to the 7th character System.out.println(str1.substring(0, 7)); // program // 1st to the 5th character
🌐
Universal Robots Forum
forum.universal-robots.com › urcap development › java
Splitting a string - Java - Universal Robots Forum
June 15, 2017 - I got a string, which I am trying to split up. The string looks like 50.5|70|10 and I am trying to get the different parts into different text fields. String[] slices = getSettings().split("|"); part_diameterTextField.setText(slices[0]); part_lengthTextField.setText(slices[1]); pin_diamete...