If you use the Apache Commons Lang3 library, you can also use the substringAfter
method of the StringUtils
utility class.
Official documentation is here.
Examples:
String value = StringUtils.substringAfter("key=value", "="); // in this case where a space is in the value (e.g. read from a file instead of a query params) String value = StringUtils.trimToEmpty(StringUtils.substringAfter("key = value", "=")); // = "value"
It manage the case where your values can contains the '=' character as it takes the first occurence.
If you have keys and values also containing '=' character it will not work (but the other methods as well); in the URL query params, such a character should be escaped anyway.
Источник
Delete everything after part of a string
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!
10 Answers 10
String result = input.split("-")[0];
String result = input.substring(0, input.indexOf("-"));
(and add relevant error handling)
Do 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 )
The apache commons StringUtils provide a substringBefore method
StringUtils.substringBefore("Stack Overflow - A place to ask stuff", " - ")
This works really nicely. I'd expect most non-trivial projects to reference Apache Commons, and this avoids the error-prone fiddling with substrings/indexing
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"
String mysourcestring = "developer is - development"; String substring = mysourcestring.substring(0,mysourcestring.indexOf("-"));
it would be written "developer is -"
Was 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.
Perhaps thats what you are looking for:
String str="Stack Overflow - A place to ask stuff"; String newStr = str.substring(0, str.indexOf("-"));
I created Sample program for all the approches and SubString seems to be fastest one.
Using builder : 54 Using Split : 252 Using Substring : 10
Below is the sample program code
for (int count = 0; count < 1000; count++) < // For JIT >long start = System.nanoTime(); //Builder StringBuilder builder = new StringBuilder( "Stack Overflow - A place to ask stuff"); builder.delete(builder.indexOf("-"), builder.length()); System.out.println("Using builder : " + (System.nanoTime() - start) / 1000); start = System.nanoTime(); //Split String string = "Stack Overflow - A place to ask stuff"; string.split("-"); System.out.println("Using Split : " + (System.nanoTime() - start) / 1000); //SubString start = System.nanoTime(); String string1 = "Stack Overflow - A place to ask stuff"; string1.substring(0, string1.indexOf("-")); System.out.println("Using Substring : " + (System.nanoTime() - start) / 1000); return null;
Источник
Remove string after last occurrence of a character
In my application, I am appending a string to create path to generate a URL. Now I want to remove that appended string on pressing back button. Suppose this is the string:
/String1/String2/String3/String4/String5
/String1/String2/String3/String4/
i have answered the question .. over [here][1] it is an easy way.. [1]: stackoverflow.com/questions/1181969/…
5 Answers 5
You can use lastIndexOf() method for same with
if (null != str && str.length() > 0 ) < int endIndex = str.lastIndexOf("/"); if (endIndex != -1) < String newstr = str.substring(0, endIndex); // not forgot to put check if(endIndex != -1) >>
This would not work for path already ending with "/", consider this path /user/etc/lib/, be careful when handling such scenario.
String whatyouaresearching = myString.substring(0, myString.lastIndexOf("/"))
@rsan Great answer, since the string whatyouaresearching includes the last "/" it will be more like: String whatyouaresearching = myString.substring(0, myString.lastIndexOf("/") + 1)
// The symbol * is used to indicate any input including null. StringUtils.substringBeforeLast(null, *) = null StringUtils.substringBeforeLast("", *) = "" StringUtils.substringBeforeLast("abcba", "b") = "abc" StringUtils.substringBeforeLast("abc", "c") = "ab" StringUtils.substringBeforeLast("a", "a") = "" StringUtils.substringBeforeLast("a", "z") = "a" StringUtils.substringBeforeLast("a", null) = "a" StringUtils.substringBeforeLast("a", "") = "a"
org.apache.commons commons-lang3 3.8
Источник
Remove part of string after or before a specific word in java
Is there a command in java to remove the rest of the string after or before a certain word; Example: Remove substring before the word "taken" before: "I need this words removed taken please" after: "taken please"
5 Answers 5
String are immutable, you can however find the word and create a substring:
public static String removeTillWord(String input, String word) < return input.substring(input.indexOf(word)); >removeTillWord("I need this words removed taken please", "taken");
use return input.substring(input.indexOf(word) +word.length()) if you want to remove including the word taken
There is apache-commons-lang class StringUtils that contains exactly you want:
e.g. public static String substringBefore(String str, String separator)
From question "Remove substring before the word "taken" " which OP explains as: before "I need this words removed taken please" after: "taken please" so as you see "taken" is part of result (after) so it was not removed.
Just to be clear, I am not saying that your approach is bad. I am just pointing that it needs some polishing.
public static String foo(String str, String remove)
If str = "I need this words removed taken please" and remove = "I need this words removed " then str.indexOf(remove) = 0 . Which in return returns str from the very beginning, i.e. doesn't remove anything.
@GeroldBroser Which is correct behaviour since as OP shown in example part which was searched needs to stay (it is part before/after it which was removed).
@Pshemo I didn't write my previous comment because it doesn't give the desired result somehow. It's the naming that's bad. What do you expect as input to a String parameter named remove? The text to be removed or the text that should stay? And should it stay or should it be removed then?
@GeroldBroser Oh, in that case I misunderstood your comment (sorry for that) and you are right, name of that variable is not correct. But just in case your comment was cause of downvote I will leave my response for other people who (like me) may misunderstand it to not downvote it further (since IMO wrong variable name is not appropriate reason to down-vote).
@GeroldBroser well, in that case, this method is all wrong because it should check if input String is null.. but I just wrote it real quick. And it should also check if indexOf returns -1. The one who asked the question should put more effort to understand it and do all the fixing.
Clean way to safely remove until a string
String input = "I need this words removed taken please"; String token = "taken"; String result = input.contains(token) ? token + StringUtils.substringAfter(string, token) : input;
Since OP provided clear requirements
Remove the rest of the string after or before a certain word
and nobody has fulfilled those yet, here is my approach to the problem. There are certain rules to the implementation, but overall it should satisfy OP's needs, if he or she comes to revisit the question.
public static String remove(String input, String separator, boolean before) < Objects.requireNonNull(input); Objects.requireNonNull(separator); if (input.trim().equals(separator)) < return separator; >if (separator.isEmpty() || input.trim().isEmpty()) < return input; >String[] tokens = input.split(separator); String target; if (before) < target = tokens[0]; >else < target = tokens[1]; >return input.replace(target, ""); >
Источник