Delete everything after part of a string
Solution 1
For example, you could do:
String result = input.split("-")[0];
or
String result = input.substring(0, input.indexOf("-"));
(and add relevant error handling)
Solution 2
The apache commons StringUtils provide a substringBefore method
StringUtils.substringBefore("Stack Overflow - A place to ask stuff", " - ")
Solution 3
Kotlin Solution
Use the built-in Kotlin substringBefore
function (Documentation):
var string = "So much text - no - more"
string = string.substringBefore(" - ") // "So much text"
It also has an optional second param, which is the return value if the delimiter is not found. The default value is the original string
string.substringBefore(" - ", "fail") // "So much text"
string.substringBefore(" -- ", "fail") // "fail"
string.substringBefore(" -- ") // "So much text - no - more"
Solution 4
You can use this
String mysourcestring = "developer is - development";
String substring = mysourcestring.substring(0,mysourcestring.indexOf("-"));
it would be written "developer is -"
Solution 5
Perhaps thats what you are looking for:
String str="Stack Overflow - A place to ask stuff";
String newStr = str.substring(0, str.indexOf("-"));
SweSnow
Updated on April 04, 2021Comments
-
SweSnow about 3 years
I have a string that is built out of three parts. The word I want the string to be (changes), a seperating part (doesn't change) and the last part which changes. I want to delete the seperating part and the ending part. The seperating part is " - " so what I'm wondering is if theres a way to delete everything after a certaint part of the string.
An example of this scenario would be if I wanted to turn this: "Stack Overflow - A place to ask stuff" into this: "Stack Overflow". Any help is appreciated!
-
Vishy over 11 yearsThat retains everything after the matching string.
-
mOna almost 10 yearsDo you know what if the primary string is like this : /name/nm1243456/lkbfwugbòwougs and I want to keep only nm123456? (I cannot use s.th like input.substring(6, directorImdbId.length() - 15) since the number of characters in the last part of string is changing (it might be 16 or 17 characters )
-
Aviral Bansal almost 8 yearsWas looking for a solution to ignore everything in a string after a substring and your answer inspired me to come up with
String substr = mysourcestring.substring(0,mysourcestring.indexOf("searchSeq")+"searchSeq".length());
So for example if I need to ignore everything in a URL after a definite substring, this can be helpful. -
Brian Agnew about 5 yearsThis works really nicely. I'd expect most non-trivial projects to reference Apache Commons, and this avoids the error-prone fiddling with substrings/indexing