Last substring of string - java

In Java we have indexOf and lastIndexOf. Is there anything like lastSubstring? It should work like :
"aaple".lastSubstring(0, 1) = "e";

Not in the standard Java API, but ...
Apache Commons has a lot of handy String helper methods in StringUtils
... including
StringUtils.right("apple",1)
http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#right(java.lang.String,%20int)
just grab a copy of commons-lang.jar from commons.apache.org

Generalizing the other responses, you can implement lastSubstring as follows:
s.substring(s.length()-endIndex,s.length()-beginIndex);

Perhaps lasIndexOf(String) ?

Wouldn't that just be
String string = "aaple";
string.subString(string.length() - 1, string.length());
?

You can use String.length() and String.length() - 1

For those looking to get a substring after some ending delimiter, e.g. parsing file.txt out of /some/directory/structure/file.txt
I found this helpful: StringUtils.substringAfterLast
public static String substringAfterLast(String str,
String separator)
Gets the substring after the last occurrence of a separator. The separator is not returned.
A null string input will return null. An empty ("") string input will return the empty string. An empty or null separator will return the empty string if the input string is not null.
If nothing is found, the empty string is returned.
StringUtils.substringAfterLast(null, *) = null
StringUtils.substringAfterLast("", *) = ""
StringUtils.substringAfterLast(*, "") = ""
StringUtils.substringAfterLast(*, null) = ""
StringUtils.substringAfterLast("abc", "a") = "bc"
StringUtils.substringAfterLast("abcba", "b") = "a"
StringUtils.substringAfterLast("abc", "c") = ""
StringUtils.substringAfterLast("a", "a") = ""
StringUtils.substringAfterLast("a", "z") = ""

I'm not aware of that sort of counterpart to substring(), but it's not really necessary. You can't efficiently find the last index with a given value using indexOf(), so lastIndexOf() is necessary. To get what you're trying to do with lastSubstring(), you can efficiently use substring().
String str = "aaple";
str.substring(str.length() - 2, str.length() - 1).equals("e");
So, there's not really any need for lastSubstring().

Related

Regex to extract a specific string in URL [duplicate]

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

Remove domain name from string java

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

Trim unwanted characters in a Java String

I have few Java Strings like below:
ab-android-regression-4.4-git
ab-ios-regression-4.4-git
ab-tablet-regression-4.4-git
However, I do not want such lengthy and unwanted names and so I want to get rid of starting ab- and ending -git part. The pattern for all the Strings is the same (starts with ab and ends with git)
Is there a function/class in Java that will help me in trimming such things? For example, something like:
String test = "ab-android-regression-4.4-git";
test.trim(ab, git)
Also, can StringUtils class help me with this? Thoughts on regular expressions?
EDITED PART: I also want to know how to eliminate the - characters in the Strings and change everything to uppercase letters
Here's a method that's more general purpose to remove a prefix and suffix from a string:
public static String trim (String str, String prefix, String suffix)
{
int indexOfLast = str.lastIndexOf(suffix);
// Note: you will want to do some error checking here
// in case the suffix does not occur in the passed in String
str = str.substring(0, indexOfLast);
return str.replaceFirst(prefix, "");
}
Usage:
String test = "ab-android-regression-4.4-git";
String trim = trim(test, "ab-", "-git"));
To remove the "-" and make uppercase, then just do:
trim = trim.replaceAll("-", " ").toUpperCase();
You can use test = test.replace("ab-", "") and similar for the "-git" or you can use test = StringUtils.removeStart(test, "ab-") and similarly, removeEnd.
I prefer the latter if you can use StringUtils because it won't ever accidentally remove the middle of the filename if those expressions are matched.
Since the parts to trim are constant in size, you should simply use substring :
yourString.substring(3, yourString.length - 4)
If your string always contains ab- at the begining and -git at the end then here is the code
String test = "ab-android-regression-4.4-git";
test=test.substring(3, s.length() - 4);
System.out.println("s is"+s); //output is android-regression-4.4
To know more about substrings click https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html

Java - removing first character of a string

In Java, I have a String:
Jamaica
I would like to remove the first character of the string and then return amaica
How would I do this?
const str = "Jamaica".substring(1)
console.log(str)
Use the substring() function with an argument of 1 to get the substring from position 1 (after the first character) to the end of the string (leaving the second argument out defaults to the full length of the string).
public String removeFirstChar(String s){
return s.substring(1);
}
In Java, remove leading character only if it is a certain character
Use the Java ternary operator to quickly check if your character is there before removing it. This strips the leading character only if it exists, if passed a blank string, return blankstring.
String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
Prints:
blankstring
foobar
moobar
Java, remove all the instances of a character anywhere in a string:
String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"
Java, remove the first instance of a character anywhere in a string:
String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"
Use substring() and give the number of characters that you want to trim from front.
String value = "Jamaica";
value = value.substring(1);
Answer: "amaica"
You can use the substring method of the String class that takes only the beginning index and returns the substring that begins with the character at the specified index and extending to the end of the string.
String str = "Jamaica";
str = str.substring(1);
substring() method returns a new String that contains a subsequence of characters currently contained in this sequence.
The substring begins at the specified start and extends to the character at index end - 1.
It has two forms. The first is
String substring(int FirstIndex)
Here, FirstIndex specifies the index at which the substring will
begin. This form returns a copy of the substring that begins at
FirstIndex and runs to the end of the invoking string.
String substring(int FirstIndex, int endIndex)
Here, FirstIndex specifies the beginning index, and endIndex specifies
the stopping point. The string returned contains all the characters
from the beginning index, up to, but not including, the ending index.
Example
String str = "Amiyo";
// prints substring from index 3
System.out.println("substring is = " + str.substring(3)); // Output 'yo'
you can do like this:
String str = "Jamaica";
str = str.substring(1, title.length());
return str;
or in general:
public String removeFirstChar(String str){
return str.substring(1, title.length());
}
public String removeFirst(String input)
{
return input.substring(1);
}
The key thing to understand in Java is that Strings are immutable -- you can't change them. So it makes no sense to speak of 'removing a character from a string'. Instead, you make a NEW string with just the characters you want. The other posts in this question give you a variety of ways of doing that, but its important to understand that these don't change the original string in any way. Any references you have to the old string will continue to refer to the old string (unless you change them to refer to a different string) and will not be affected by the newly created string.
This has a number of implications for performance. Each time you are 'modifying' a string, you are actually creating a new string with all the overhead implied (memory allocation and garbage collection). So if you want to make a series of modifications to a string and care only about the final result (the intermediate strings will be dead as soon as you 'modify' them), it may make more sense to use a StringBuilder or StringBuffer instead.
I came across a situation where I had to remove not only the first character (if it was a #, but the first set of characters.
String myString = ###Hello World could be the starting point, but I would only want to keep the Hello World. this could be done as following.
while (myString.charAt(0) == '#') { // Remove all the # chars in front of the real string
myString = myString.substring(1, myString.length());
}
For OP's case, replace while with if and it works aswell.
You can simply use substring().
String myString = "Jamaica"
String myStringWithoutJ = myString.substring(1)
The index in the method indicates from where we are getting the result string, in this case we are getting it after the first position because we dont want that "J" in "Jamaica".
Another solution, you can solve your problem using replaceAll with some regex ^.{1} (regex demo) for example :
String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.
public static String removeLeadingChar(String str, char ch) {
int idx = 0;
while ((idx < str.length()) && (str.charAt(idx) == ch))
idx++;
return str.substring(idx);
}
##KOTLIN
#Its working fine.
tv.doOnTextChanged { text: CharSequence?, start, count, after ->
val length = text.toString().length
if (length==1 && text!!.startsWith(" ")) {
tv?.setText("")
}
}

How can I trim beginning and ending double quotes from a string?

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

Categories

Resources