The accepted answer is correct but it doesn't tell you how to use it. This is how you use indexOf and substring functions together.

String filename = "abc.def.ghi";     // full file name
int iend = filename.indexOf("."); //this finds the first occurrence of "." 
//in string thus giving you the index of where it is in the string

// Now iend can be -1, if lets say the string had no "." at all in it i.e. no "." is found. 
//So check and account for it.

String subString;
if (iend != -1) 
{
    subString= filename.substring(0 , iend); //this will give abc
}
Answer from Sam B on Stack Overflow
🌐
Sabe
sabe.io › blog › java-substring-before-character
How to get the Substring before a Character in Java - Sabe.io
June 28, 2022 - JAVAString string = "Hello:World"; ... character you want to extract. With this index, you can then use the substring() method to get the substring before that index....
Discussions

java - how to find before and after sub-string in a string - Stack Overflow
I have a string say 123dance456 which I need to split into two strings containing the first sub-string before the sub-string dance (i.e. 123) and after the sub-string dance (i.e. 456). I need to find More on stackoverflow.com
🌐 stackoverflow.com
[Java] How can I get all numbers from a String before a white space?
Split it by whitespace and take the first element in the array it should be your first number More on reddit.com
🌐 r/learnprogramming
4
1
May 19, 2022
java - How to split String before first comma? - Stack Overflow
I have an overriding method with String which returns String in format of: "abc,cde,def,fgh" I want to split the string content into two parts: String before first comma and String after first c... More on stackoverflow.com
🌐 stackoverflow.com
June 2, 2015
How to find all occurrences of a substring in a string while ignore some characters in Python?
You could use re for this. ex import re long_string = 'this is a t`es"t. Does the test work?' small_string = "test" chars_to_ignore = ['"', '`'] print(re.findall(f"[{''.join(chars_to_ignore)}]*".join(small_string), long_string)) More on reddit.com
🌐 r/learnpython
6
1
July 25, 2024
🌐
Baeldung
baeldung.com › home › java › java string › get substring from string in java
Get Substring from String in Java | Baeldung
July 21, 2024 - Similarly, the substringBefore method gets the substring before the first occurrence of a separator.
🌐
W3Docs
w3docs.com › java
In java how to get substring from a string till a character c?
To get a substring from a string in Java up until a certain character, you can use the indexOf method to find the index of the character and then use the substring method to extract the substring.
🌐
Logfetch
logfetch.com › java-get-substring-before-char
How to Get the Substring Before a Character in Java - LogFetch
August 31, 2021 - String substr = StringUtils.substringBefore(str, ":"); // "name" ... What is the double colon (::) in Java?
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-string-substring
Master Java Substring Method: Examples, Syntax, and Use Cases | DigitalOcean
February 20, 2025 - substring(int beginIndex, int endIndex): The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is (endIndex - beginIndex). Both the string substring methods can throw IndexOutOfBoundsException if any of the below ...
🌐
Dot Net Perls
dotnetperls.com › between-before-after-java
Java - String Between, Before, After - Dot Net Perls
-1) { return ""; } int adjustedPosA = posA + a.length(); if (adjustedPosA >= posB) { return ""; } return value.substring(adjustedPosA, posB); } static String before(String value, String a) { // Return substring containing all characters before a string.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Java Remove All Characters Before Specific One Character - Java Code Geeks
September 4, 2024 - 2. Check Existence: Ensure the character exists in the string (index != -1). 3. Extract Substring: Use substring(index) to get the part of the string starting from the target character.
Find elsewhere
Top answer
1 of 6
54

You can use String.split(String regex). Just do something like this:

String s = "123dance456";
String[] split = s.split("dance");
String firstSubString = split[0];
String secondSubString = split[1];

Please note that if "dance" occurs more than once in the original string, split() will split on each occurrence -- that's why the return value is an array.

2 of 6
22

You can do this:

String str = "123dance456";
String substr = "dance";
String before = str.substring(0, str.indexOf(substr));
String after = str.substring(str.indexOf(substr) + substr.length());

Or

String str = "123dance456";
String substr = "dance";
String[] parts = str.split(substr);
String before = parts[0];
String after = parts[1];

It is noteworthy that the second answer not work if we have more than one occurrence of the substring. To that end, if we only want the first one to be recognized, it would be safer to call split with a limit:

String[] parts = str.split(substr, 2);

which ensures that the returned array has at most two elements. Also, since split will interpret its input as a regular expression we have to be wary of invalid regular expression syntax. As such, I would much rather the first solution, since it works irrespective of the composition of the original substring.

To make the first answer more efficient -- as it is my preferred answer -- then, we would need to remember the position of the substring:

final int position = str.indexOf(substr);
if (position >= 0) {
    //if the substring does occur within the string, set the values accordingly
    before = str.substring(0, position);
    after = str.substring(position + substr.length());
} else {
    //otherwise, default to the empty string (or some other value)
    before = "";
    after = "";
}

It always pays to pay attention to these little edge cases.

🌐
GeeksforGeeks
geeksforgeeks.org › java › searching-for-characters-and-substring-in-a-string-in-java
Searching For Characters and Substring in a String in Java - GeeksforGeeks
July 23, 2025 - Java · public class CharAtExample { public static void main(String[] args) { String s = "GeeksforGeeks is a computer science portal"; // Get the character at index 10 char ch = s.charAt(10); System.out.println("Character at index 10: " + ch); } } Output · Character at index 10: e · Finds the first occurrence of a substring.
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-string-substring-method-example
Java String substring() Method with examples
The beginIndex is inclusive, that ... than the length of String (beginIndex<0||> length of String). ... Returns a substring starting from specified beginIndex till the character present at endIndex – 1....
🌐
Baeldung
baeldung.com › home › java › java string › remove all characters before a specific character in java
Remove All Characters Before a Specific Character in Java | Baeldung
May 4, 2024 - If the targetChar is found (index != -1), it extracts the substring starting from the index using substring(). Then we validate the result string using assertEquals() to ensure it matches the expected value (World!). Otherwise, it returns the original string. Another approach involves using regular expressions (regex) to replace all characters before the specified character with an empty string.
🌐
javaspring
javaspring.net › blog › in-java-how-to-get-substring-from-a-string-till-a-character-c
How to Extract Substring Before First Specific Character in Java: Filename Prefix Example — javaspring.net
Suppose you have a filename like ... ... The delimiter is a specific character (e.g., "_"). Only the substring before the first occurrence of the delimiter is needed (ignore subsequent delimiters)....
🌐
W3Schools
w3schools.com › java › ref_string_substring.asp
Java String substring() Method
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A ... The substring() method returns a substring from the string.
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.text › substring-before.html
substringBefore - Kotlin Programming Language
March 21, 2022 - Returns true if this char sequence contains the specified other sequence of characters as a substring.
🌐
TutorialsPoint
tutorialspoint.com › article › get-the-substring-before-the-last-occurrence-of-a-separator-in-java
Get the substring before the last occurrence of a separator in Java
June 27, 2020 - public class Demo { public static void main(String[] args) { String str = "David-Warner"; String separator ="-"; int sepPos = str.lastIndexOf(separator); if (sepPos == -1) { System.out.println(""); } System.out.println("Substring before last separator = "+str.substring(0,sepPos)); } }