Remove string after last occurrence of a character - java

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
Now I want a string like this:
/String1/String2/String3/String4/
How can I do this?

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

String whatyouaresearching = myString.substring(0, myString.lastIndexOf("/"))

You can use org.apache.commons.lang3.StringUtils.substringBeforeLast which is null-safe.
From the javadoc:
// 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"
Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8</version>
</dependency>

Easiest way is ...
String path = "http://zareahmer.com/questions/anystring";
int pos = path.lastIndexOf("/");
String x =path.substring(pos+1 , path.length()-1);
now x has the value stringAfterlastOccurence

The third line in Nepster's answer should be
String x =path.substring(pos+1 , path.length());
and not String x =path.substring(pos+1 , path.length()-1); since substring() method takes the end+1 offset as the second parameter.

Related

Remove parts of String? [duplicate]

I want to remove a part of string from one character, that is:
Source string:
manchester united (with nice players)
Target string:
manchester united
There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class. If you are looking to replace a substring you can get the substring using the substring API.
For example
String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));
To replace content within "()" you can use:
int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));
String Replace
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
Edit:
By Index
s = s.substring(0, s.indexOf("(") - 1);
Use String.Replace():
http://www.daniweb.com/software-development/java/threads/73139
Example:
String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");
originalString.replaceFirst("[(].*?[)]", "");
https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()
Using StringBuilder, you can replace the following way.
StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");
You should use the substring() method of String object.
Here is an example code:
Assumption: I am assuming here that you want to retrieve the string till the first parenthesis
String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.
String[] output = originalString.split(" (");
String result = output[0];
Using StringUtils from commons lang
A null source string will return null. An empty ("") source string will return the empty string. A null remove string will return the source string. An empty ("") remove string will return the source string.
String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"
If you just need to remove everything after the "(", try this. Does nothing if no parentheses.
StringUtils.substringBefore(str, "(");
If there may be content after the end parentheses, try this.
String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")");
To remove end spaces, use str.trim()
Apache StringUtils functions are null-, empty-, and no match- safe
Kotlin Solution
If you are removing a specific string from the end, use removeSuffix (Documentation)
var text = "one(two"
text = text.removeSuffix("(two") // "one"
If the suffix does not exist in the string, it just returns the original
var text = "one(three"
text = text.removeSuffix("(two") // "one(three"
If you want to remove after a character, use
// Each results in "one"
text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")
You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar
The Full List is here: (Documentation)
// Java program to remove a substring from a string
public class RemoveSubString {
public static void main(String[] args) {
String master = "1,2,3,4,5";
String to_remove="3,";
String new_string = master.replace(to_remove, "");
// the above line replaces the t_remove string with blank string in master
System.out.println(master);
System.out.println(new_string);
}
}
You could use replace to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.
str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched

Java StringUtils.stripEnd with period, hyphen or underscore

I'm trying to strip trailing characters off of a string using StringUtils.stripEnd, and noticed if I try to strip "_FOO" from "FOO_FOO", this returns an empty string. For example,
import org.apache.commons.lang3.StringUtils;
public class StripTest {
public static void printStripped(String s1, String suffix){
String result = StringUtils.stripEnd(s1, suffix);
System.out.println(String.format("Stripping '%s' from %s --> %s", suffix, s1, result));
}
public static void main(String[] args) {
printStripped("FOO.BAR", ".BAR");
printStripped("BAR.BAR", ".BAR");
printStripped("FOO_BAR", "_BAR");
printStripped("BAR_BAR", "_BAR");
printStripped("FOO-BAR", "-BAR");
printStripped("BAR-BAR", "-BAR");
}
}
Which outputs
Stripping '.BAR' from FOO.BAR --> FOO
Stripping '.BAR' from BAR.BAR -->
Stripping '_BAR' from FOO_BAR --> FOO
Stripping '_BAR' from BAR_BAR -->
Stripping '-BAR' from FOO-BAR --> FOO
Stripping '-BAR' from BAR-BAR -->
Can someone explain this behavior? Didn't see any examples from docs of this case. Using Java 7.
Look at the documentation and examples present in the StringUtils Javadoc:
Strips any of a set of characters from the end of a String.
A null input String returns null. An empty string ("") input returns the empty string.
If the stripChars String is null, whitespace is stripped as defined by Character.isWhitespace(char).
StringUtils.stripEnd(null, *) = null
StringUtils.stripEnd("", *) = ""
StringUtils.stripEnd("abc", "") = "abc"
StringUtils.stripEnd("abc", null) = "abc"
StringUtils.stripEnd(" abc", null) = " abc"
StringUtils.stripEnd("abc ", null) = "abc"
StringUtils.stripEnd(" abc ", null) = " abc"
StringUtils.stripEnd(" abcyx", "xyz") = " abc"
StringUtils.stripEnd("120.00", ".0") = "12"
This is not what you want, as it will strip the SET of characters anywhere from the end. I believe you are looking for removeEnd(...)
Removes a substring only if it is at the end of a source string, otherwise returns the source string.
A null source string will return null. An empty ("") source string will return the empty string. A null search string will return the source string.
StringUtils.removeEnd(null, *) = null
StringUtils.removeEnd("", *) = ""
StringUtils.removeEnd(*, null) = *
StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeEnd("abc", "") = "abc"
removeEnd(...) operates not a set of characters, but instead a substring, which is what you are trying to extract.

Get URL part only android

I have the URL
http://www.facebook.com/post/ll.html
I want to spilt the url into http://www.facebook.com/post/ and ll.html
Please help
One way of doing this is:
String myStr = "http://www.facebook.com/post/ll.html";
String strEnd = myStr.substring(myStr.lastIndexOf('/')+1);
strEnd will have the string you desire.
String x = "http://www.facebook.com/post/ll.html";
String[] splits = x.split("/");
String last = splits[splits.length - 1];
String first = x.substring(0, x.length() - last.length());
System.out.println(last); // 11.html
System.out.println(first); // http://www.facebook.com/post/
I think the best way to approach this is to also use the URL class, as there are a lot of gotchas if you just do simple string parsing. For your example:
// Get ll.html
String filePart = url.getPath().substring(url.getPath().lastIndexOf('/')+1);
// Get /post/
String pathPart = url.getPath().substring(0, url.getPath().lastIndexOf('/')+1);
// Cut off full URL at end of first /post/
pathPart = url.toString().substring(0, url.toString().indexOf(pathPart)+pathPart.length());
This will even cope with URLs like http://www.facebook.com:80/ll.html/ll.html#foo/bar?wibble=1/ll.html.
Try this:
if (null != str && str.length() > 0 )
{
int endIndex = str.lastIndexOf("/");
if (endIndex != -1)
{
String firststringurl = str.substring(0, endIndex);
String secondstringurl = str.substring(endIndex);
}
}

How to get the string before .(dot) and after /(last) slash in Java

I have a string like this:
"core/pages/viewemployee.jsff"
From this code, I need to get "viewemployee". How do I get this using Java?
Suppose that you have that string saved in a variable named myString.
String myString = "core/pages/viewemployee.jsff";
String newString = myString.substring(myString.lastIndexOf("/")+1, myString.indexOf("."));
But you need to make the same control before doing substring in this one, because if there aren't those characters you will get a "-1" from lastIndexOf(), or indexOf(), and it will break your substring invocation.
I suggest looking for the Javadoc documentation.
You can solve this with regex (given you only need a group of word characters between the last "/" and "."):
String str="core/pages/viewemployee.jsff";
str=str.replaceFirst(".*/(\\w+).*","$1");
System.out.println(str); //prints viewemployee
You can split the string first with "/" so that you can have each folder and the file name got separated. For this example, you will have "core", "pages" and "viewemployee.jsff". I assume you need the file name without the extension, so just apply same split action with "." seperator to the last token. You will have filename without extension.
String myStr = "core/pages/viewemployee.bak.jsff";
String[] tokens = myStr.split("/");
String[] fileNameTokens = tokens[tokens.length - 1].split("\\.");
String fileNameStr = "";
for(int i = 0; i < fileNameTokens.length - 1; i++) {
fileNameStr += fileNameTokens[i] + ".";
}
fileNameStr = fileNameStr.substring(0, fileNameStr.length() - 1);
System.out.print(fileNameStr) //--> "viewemployee.bak"
These are file paths. Consider using File.getName(), especially if you already have the File object:
File file = new File("core/pages/viewemployee.jsff");
String name = file.getName(); // --> "viewemployee.jsff"
And to remove the extension:
String res = name.split("\\.[^\\.]*$")[0]; // --> "viewemployee"
With this we can handle strings like "../viewemployee.2.jsff".
The regex matches the last dot, zero or more non-dots, and the end of the string. Then String.split() treats these as a delimiter, and ignores them. The array will always have one element, unless the original string is ..
The below will get you viewemployee.jsff:
int idx = fileName.replaceAll("\\", "/").lastIndexOf("/");
String fileNameWithExtn = idx >= 0 ? fileName.substring(idx + 1) : fileName;
To remove the file Extension and get only viewemployee, similarly:
idx = fileNameWithExtn.lastIndexOf(".");
String filename = idx >= 0 ? fileNameWithExtn.substring(0,idx) : fileNameWithExtn;

Using regex on XML, avoid greedy match

It looks simple problem , but I'll apprisiate any help here :
I need to swap password value (can be any value) to "****"
The origunal sting is string resived from xml
The problem is that I getting as output only line:
<parameter><value>*****</value></parameter>
But I need the whole string as output only with password value replaced
Thank you in advance
String originalString = "<parameter>" +
"<name>password</name>"+
"<value>my123pass</value>"+
"</parameter>"+
"<parameter>"+
"<name>LoginAttempt</name>"+
"<value>1</value>"+
"</parameter>";
System.out.println("originalString: "+originalString);
Pattern pat = Pattern.compile("<name>password</name><value>.*</value>");
Matcher mat = pat.matcher(originalString);
System.out.println("NewString: ");
System.out.print(mat.replaceFirst("<value>***</value>"));
mat.reset();
If I'm not mistaken, you want to change the password in the string with *'s. You can do it by using String methods directly. Just get the last index of the starting value tag and iterate until you reach a "<", replacing the value between those two with *'s. Something like this:
int from = originalString.lastIndexOf("<name>password</name><value>");
bool endIteration = false;
for(i = from + 1 ; i < originalString.length() && !endIteration ; i ++) {
if(originalString.toCharArray()[i] == '<')
endIteration = true;
else {
originalString.toCharArray()[i] = '*';
}
}
EDIT: There is another way making a proper use of all the String class goodies:
int from = originalString.lastIndexOf("<name>password</name><value>");
int to = originalString.indexOf("</value>", from);
Arrays.fill(originalString.toCharArray(), from, to, '*');

Categories

Resources