Java string delete all after symbol

How to remove all characters before a specific character in Java?

I have a string and I’m getting value through a html form so when I get the value it comes in a URL so I want to remove all the characters before the specific charater which is = and I also want to remove this character. I only want to save the value that comes after = because I need to fetch that value from the variable.. EDIT : I need to remove the = too since I’m trying to get the characters/value in string after it.

@ItamarGreen I don’t know how to do it since I’m a beginner so I searched it up on the internet and I didn’t find anything that I could understand so please if you know help me understand it

What you really want is parse query parameters. See this question: stackoverflow.com/questions/13592236/…

6 Answers 6

String s = "the text=text"; String s1 = s.substring(s.indexOf("=") + 1); s1.trim(); 

then s1 contains everything after = in the original string.

s1.trim()

.trim() removes spaces before the first character (which isn’t a whitespace, such as letters, numbers etc.) of a string (leading spaces) and also removes spaces after the last character (trailing spaces).

Just to add, if anyone wants to get the text before =, you can use this: String s1 = s.substring(0, s.indexOf(«=»)); then s1 contains everything before = in the original string.

While there are many answers. Here is a regex example

String test = "eo21jüdjüqw=realString"; test = test.replaceAll(".+=", ""); System.out.println(test); // prints realString 

.+ matches any character (except for line terminators)
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
= matches the character = literally (case sensitive)

Читайте также:  Qt designer python программа

This is also a shady copy paste from https://regex101.com/ where you can try regex out.

You can split the string from the = and separate in to array and take the second value of the array which you specify as after the = sign For example:

String CurrentString = «Fruit = they taste good»; String[] separated = CurrentString.split(«=»); separated[0]; // this will contain «Fruit» separated[1]; //this will contain «they teste good»

then separated[1] contains everything after = in the original string.

I know this is asked about Java but this seems to also be the first search result for Kotlin so you should know that Kotlin has the String.substringAfter(delimiter: String, missingDelimiterValue: String = this) extension for this case.

val index = indexOf(delimiter) return if (index == -1) missingDelimiterValue else substring(index + delimiter.length, length) 

Maybe locate the first occurrence of the character in the URL String. For Example:

String URL = "http://test.net/demo_form.asp?name1=stringTest"; int index = URL.indexOf(" mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Dec 1, 2016 at 12:47
answered Dec 1, 2016 at 12:41
1
    @sha If you don't want to include the "=", simply increment the index by 1.
    – yogur
    Dec 1, 2016 at 12:46
Add a comment|
1

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, ""); > 

Источник

Оцените статью