Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add StringUtils.substringBeforeLast(String, int) #967

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/main/java/org/apache/commons/lang3/StringUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -8690,6 +8690,41 @@ public static String substringBefore(final String str, final String separator) {
}
return str.substring(0, pos);
}

/**
* Gets the substring before the last occurrence of a separator.
* The separator is not returned.
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.</p>
*
* <p>If nothing is found, the string input is returned.</p>
*
* <pre>
* 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"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the character (Unicode code point) to search.
* @return the substring before the last occurrence of the separator,
* {@code null} if null String input
* @since 3.12.1
*/
public static String substringBeforeLast(final String str, final int separator) {
if (isEmpty(str)) {
return str;
}
final int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}

/**
* Gets the substring before the last occurrence of a separator.
Expand Down