I have a string:
/abc/def/ghfj.doc
I would like to extract ghfj.doc from this, i.e. the substring after the last /, or first / from right.
Could someone please provide some help?
String example = "/abc/def/ghfj.doc";
System.out.println(example.substring(example.lastIndexOf("/") + 1));
A very simple implementation with String.split():
String path = "/abc/def/ghfj.doc";
// Split path into segments
String segments[] = path.split("/");
// Grab the last segment
String document = segments[segments.length - 1];
what have you tried?
it's very simple:
String s = "/abc/def/ghfj.doc";
s.substring(s.lastIndexOf("/") + 1)
Another way is to use this.
String path = "/abc/def/ghfj.doc"
String fileName = StringUtils.substringAfterLast(path, "/");
If you pass null to this method it will return null. If there is no match with separator it will return empty string.
You can use Apache commons:
For substring after last occurrence use this method.
And for substring after first occurrence equivalent method is here.
This can also get the filename
import java.nio.file.Paths;
import java.nio.file.Path;
Path path = Paths.get("/abc/def/ghfj.doc");
System.out.println(path.getFileName().toString());
Will print ghfj.doc
In Kotlin you can use substringAfterLast, specifying a delimiter.
val string = "/abc/def/ghfj.doc"
val result = url.substringAfterLast("/")
println(result)
// It will show ghfj.doc
From the doc:
Returns a substring after the last occurrence of delimiter. If the string does not contain the delimiter, returns missingDelimiterValue which defaults to the original string.
With Guava do this:
String id="/abc/def/ghfj.doc";
String valIfSplitIsEmpty="";
return Iterables.getLast(Splitter.on("/").split(id),valIfSplitIsEmpty);
Eventually configure the Splitter and use
Splitter.on("/")
.trimResults()
.omitEmptyStrings()
...
Also take a look into this article on guava Splitter and this article on guava Iterables
I think that would be better if we use directly the split function
String toSplit = "/abc/def/ghfj.doc";
String result[] = toSplit.split("/");
String returnValue = result[result.length - 1]; //equals "ghfj.doc"
java android
in my case
I want to change from
~/propic/........png
anything after /propic/ doesn't matter what before it
........png
finally, I found the code in Class StringUtils
this is the code
public static String substringAfter(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return "";
}
final int pos = str.indexOf(separator);
if (pos == 0) {
return str;
}
return str.substring(pos + separator.length());
}
Related
I have a string which looks like this
String str = "domain\ABC";
String str = "domain1\DEF";
How do i write a common function to remove the "domain\" or "domain1\" and just have the string after the the '\'. I tried a couple of different ways but none seem to work.
This is what i have tried.
String[] str = remoteUser.split(remoteUser, '\\');
No need for split() or regex for this, as that is overkill. It's a simple indexOf() operation.
How do i write a common function ... ?
Like this:
public static String removeDomain(String input) {
return input.substring(input.indexOf('/') + 1);
}
The code relies on the fact indexOf() returns -1 if / is not found, so the + 1 will make that 0 and substring(0) then returns input string as-is.
Try it like this.
String str = "domain\\ABC";
String[] split = str.split("\\\\");
//Assign the second element of the array. This only works if you know for sure that there is only one \ in the string.
String withoutSlash = split[1];
Hope it helps.
You might use replaceAll:
System.out.println("domain\\ABC".replaceAll("^.*\\\\",""));
It will replace everything starting at the beginning of the string, until \ symbol.
Try this:
static String getPath(String url) {
int pos = url.indexOf('\');
return pos >= 0 ? url.substring(pos + 1) : url;
}
I want to parse the following and store it as a new string, with the condition that mawi is stored and everything else is removed.
<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>
One solution I suppose could be a substring starting with the first character after the first > and ending two characters before the first -. All the data is identical. The result is a String with value mawi.
String initial = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
String substring = initial.substring(example.indexOf(">"));
Not sure where to go from here... Any thoughts?
Although the below code do the trick, I suggest you to use Jsoup or XML Parse if you are processing multiple strings like this
Pattern pattern = Pattern.compile("<ns0:Assignee>(.+?)</ns0:Assignee>");
Matcher matcher = pattern.matcher("<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>");
matcher.find();
String result = matcher.group(1);
String finalString = result.split(" - ")[0];
System.out.println(finalString); // mawi
If all the strings are built like your example string, you could go with this:
initial.substring(initial.indexOf('>') + 1, initial.indexOf(' '));
Note the + 1 at the start index.
When your Strings are more complicated, I would recommend either using a library for working with XML or using Regular Expressions.
So now you got substring which is equal to: >mawi - Manfred Wilson</ns0:Assignee>.
Now, you can substring your substring again to find only mawi, like this;
String initial = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
String midSub = initial.substring(initial.indexOf('>'));
String finalSub = midSub.substring(1, midSub.indexOf(' ')); // 1 because we still have `>`
System.out.println(finalSub);
Or, one liner:
String finalSub = initial.substring(initial.indexOf('>')+1, initial.indexOf(' '));
show this:
String s = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
s = s.substring(s.indexOf("<ns0:Assignee>")+"<ns0:Assignee>".length(), s.indexOf("</ns0:Assignee>"));
public class string {
public static void main(String[] args) {
String s = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
s = s.substring(14, 18);
System.out.println(s);
}
}
Hi I need to split a String in java based on conditions
the String might be in two formats
1. IF the format is like this WG/A/0-5 then I need to check if the last part starts with "0-" then I need the middle part to be extracted (ie:"A")
2.The Second format is WG/A/3-3 here it is 3-3 ie:other than 0) here I need to extract (A/3) .
I have tried like this
String parent = StringPool.BLANK;
if(wgCode.split(StringPool.FORWARD_SLASH)[2].startsWith("0-")) {
parent = wgCode.split(StringPool.FORWARD_SLASH)[1];
} else if(!wgCode.split(StringPool.FORWARD_SLASH)[2].startsWith("0-")) {
parent = wgCode.split(StringPool.FORWARD_SLASH)[1]+"/"+wgCode.split(StringPool.FORWARD_SLASH)[2].split("-")[0];
}
_log.info("parent parent"+parent);
Use Regular Expressions and String.contains to check your conditions and String.indexOf and String.substring to split your String.
The following method will work for your example:
public String getString(String input)
{
if(input.matches(".*/.*/0.*"))
{
String yourString = input.substring(input.indexOf("/")+1);
yourString = yourString.substring(0, yourString.indexOf("/"));
return yourString;
}
else
{
String yourString = input.substring(input.indexOf("/")+1);
yourString = yourString.substring(0, yourString.indexOf("/")+2);
return yourString;
}
}
With the regular expression .*/.*/0.* you find all Strings that start with a 0 after the second /.
use String#contains(String) to check whether 0- is there nor not.
String str="WG/A/0-5";
String str1="WG/A/3-3";
if(str.contains("0-"))
System.out.println(str.substring(str.indexOf("/")+1,str.indexOf("/",str.indexOf("/") + 1)));//A
if(!str1.contains("0-"))
System.out.println(str1.substring(str1.indexOf("/")+1,str1.indexOf("-")));//A/3
Maybe something like this:
String input = "WG/A/0-5";
String[] parts = input.split("/");
if( parts[2].charAt(0) == '0' ){
......
String charAt, substring should solve your problem:
String myValue = input.charAt(5) == '0' ? input.substring(3, 4) : input
.substring(3, 6);
I am looking to remove parts of a string if it ends in a certain string.
An example would be to take this string: "am.sunrise.ios#2x.png"
And remove the #2x.png so it looks like: "am.sunrise.ios"
How would I go about checking to see if the end of a string contains "#2x.png" and remove it?
You could check the lastIndexOf, and if it exists in the string, use substring to remove it:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
int index = str.lastIndexOf(search);
if (index > 0) {
str = str.substring(0, index);
}
Assuming you have a string initialized as String file = "am.sunrise.ios#2x.png";.
if(file.endsWith("#2x.png"))
file = file.substring(0, file.lastIndexOf("#2x.png"));
The endsWith(String) method returns a boolean determining if the string has a certain suffix. Depending on that you can replace the string with a substring of itself starting with the first character and ending before the index of the character that you are trying to remove.
private static String removeSuffixIfExists(String key, String suffix) {
return key.endswith(suffix)
? key.substring(0, key.length() - suffix.length())
: key;
}
}
String suffix = "#2x.png";
String key = "am.sunrise.ios#2x.png";
String output = removeSuffixIfExists(key, suffix);
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
word = word.replace("#2x.png", "");
System.out.println(word);
}
If you want to generally remove entire content of string from # till end you can use
yourString = yourString.replaceAll("#.*","");
where #.* is regex (regular expression) representing substring starting with # and having any character after it (represented by .) zero or more times (represented by *).
In case there will be no #xxx part your string will be unchanged.
If you want to change only this particular substring #2x.png (and not substirng like #3x.png) while making sure that it is placed at end of your string you can use
yourString = yourString.replaceAll("#2x\\.png$","");
where
$ represents end of string
\\. represents . literal (we need to escape it since like shown earlier . is metacharacter representing any character)
Since I was trying to do this on an ArrayList of items similarly styled I ended up using the following code:
for (int image = 0; image < IBImages.size(); image++) {
IBImages.set(image, IBImages.get(image).split("~")[0].split("#")[0].split(".png")[0]);
}
If I have a list of images with the names
[am.sunrise.ios.png, am.sunrise.ios#2x.png, am.sunrise.ios#3x.png, am.sunrise.ios~ipad.png, am.sunrise.ios~ipad#2x.png]
This allows me to split the string into 2 parts.
For example, "am.sunrise.ios~ipad.png" will be split into "am.sunrise.ios" and "~ipad.png" if I split on "~". I can just get the first part back by referencing [0]. Therefore I get what I'm looking for in one line of code.
Note that image is "am.sunrise.ios~ipad.png"
You could use String.split():
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
String[] parts = word.split("#");
if (parts.length == 2) {
System.out.println("looks like user#host...");
System.out.println("User: " + parts[0]);
System.out.println("Host: " + parts[1]);
}
}
Then you haven an array of Strings, where the first element contains the part before "#" and the second element the part after the "#".
Combining the answers 1 and 2:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
if (str.endsWith(search)) {
str = str.substring(0, str.lastIndexOf(search));
}
I would like to trim a beginning and ending double quote (") from a string.
How can I achieve that in Java? Thanks!
You can use String#replaceAll() with a pattern of ^\"|\"$ for this.
E.g.
string = string.replaceAll("^\"|\"$", "");
To learn more about regular expressions, have al ook at http://regular-expression.info.
That said, this smells a bit like that you're trying to invent a CSV parser. If so, I'd suggest to look around for existing libraries, such as OpenCSV.
To remove the first character and last character from the string, use:
myString = myString.substring(1, myString.length()-1);
Also with Apache StringUtils.strip():
StringUtils.strip(null, *) = null
StringUtils.strip("", *) = ""
StringUtils.strip("abc", null) = "abc"
StringUtils.strip(" abc", null) = "abc"
StringUtils.strip("abc ", null) = "abc"
StringUtils.strip(" abc ", null) = "abc"
StringUtils.strip(" abcyx", "xyz") = " abc"
So,
final String SchrodingersQuotedString = "may or may not be quoted";
StringUtils.strip(SchrodingersQuotedString, "\""); //quoted no more
This method works both with quoted and unquoted strings as shown in my example. The only downside is, it will not look for strictly matched quotes, only leading and trailing quote characters (ie. no distinction between "partially and "fully" quoted strings).
If the double quotes only exist at the beginning and the end, a simple code as this would work perfectly:
string = string.replace("\"", "");
Kotlin
In Kotlin you can use String.removeSurrounding(delimiter: CharSequence)
E.g.
string.removeSurrounding("\"")
Removes the given delimiter string from both the start and the end of this string if and only if it starts with and ends with the delimiter.
Otherwise returns this string unchanged.
The source code looks like this:
public fun String.removeSurrounding(delimiter: CharSequence): String = removeSurrounding(delimiter, delimiter)
public fun String.removeSurrounding(prefix: CharSequence, suffix: CharSequence): String {
if ((length >= prefix.length + suffix.length) && startsWith(prefix) && endsWith(suffix)) {
return substring(prefix.length, length - suffix.length)
}
return this
}
This is the best way I found, to strip double quotes from the beginning and end of a string.
someString.replace (/(^")|("$)/g, '')
First, we check to see if the String is doubled quoted, and if so, remove them. You can skip the conditional if in fact you know it's double quoted.
if (string.length() >= 2 && string.charAt(0) == '"' && string.charAt(string.length() - 1) == '"')
{
string = string.substring(1, string.length() - 1);
}
Using Guava you can write more elegantly CharMatcher.is('\"').trimFrom(mystring);
I am using something as simple as this :
if(str.startsWith("\"") && str.endsWith("\""))
{
str = str.substring(1, str.length()-1);
}
To remove one or more double quotes from the start and end of a string in Java, you need to use a regex based solution:
String result = input_str.replaceAll("^\"+|\"+$", "");
If you need to also remove single quotes:
String result = input_str.replaceAll("^[\"']+|[\"']+$", "");
NOTE: If your string contains " inside, this approach might lead to issues (e.g. "Name": "John" => Name": "John).
See a Java demo here:
String input_str = "\"'some string'\"";
String result = input_str.replaceAll("^[\"']+|[\"']+$", "");
System.out.println(result); // => some string
Edited: Just realized that I should specify that this works only if both of them exists. Otherwise the string is not considered quoted. Such scenario appeared for me when working with CSV files.
org.apache.commons.lang3.StringUtils.unwrap("\"abc\"", "\"") = "abc"
org.apache.commons.lang3.StringUtils.unwrap("\"abc", "\"") = "\"abc"
org.apache.commons.lang3.StringUtils.unwrap("abc\"", "\"") = "abc\""
The pattern below, when used with java.util.regex.Matcher, will match any string between double quotes without affecting occurrences of double quotes inside the string:
"[^\"][\\p{Print}]*[^\"]"
Matcher m = Pattern.compile("^\"(.*)\"$").matcher(value);
String strUnquoted = value;
if (m.find()) {
strUnquoted = m.group(1);
}
Modifying #brcolow's answer a bit
if (string != null && string.length() >= 2 && string.startsWith("\"") && string.endsWith("\"") {
string = string.substring(1, string.length() - 1);
}
private static String removeQuotesFromStartAndEndOfString(String inputStr) {
String result = inputStr;
int firstQuote = inputStr.indexOf('\"');
int lastQuote = result.lastIndexOf('\"');
int strLength = inputStr.length();
if (firstQuote == 0 && lastQuote == strLength - 1) {
result = result.substring(1, strLength - 1);
}
return result;
}
find indexes of each double quotes and insert an empty string there.
public String removeDoubleQuotes(String request) {
return request.replace("\"", "");
}
Groovy
You can subtract a substring from a string using a regular expression in groovy:
String unquotedString = theString - ~/^"/ - ~/"$/
Scala
s.stripPrefix("\"").stripSuffix("\"")
This works regardless of whether the string has or does not have quotes at the start and / or end.
Edit: Sorry, Scala only