Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the substring before the last occurrence of a separator in Java
We have the following string with a separator.
String str = "David-Warner";
We want the substring before the last occurrence of a separator. Use the lastIndexOf() method.
For that, you need to get the index of the separator using indexOf()
String separator ="-";
int sepPos = str.lastIndexOf(separator);
System.out.println("Substring before last separator = "+str.substring(0,sepPos));
The following is an example.
Example
public class Demo {
public static void main(String[] args) {
String str = "David-Warner";
String separator ="-";
int sepPos = str.lastIndexOf(separator);
if (sepPos == -1) {
System.out.println("");
}
System.out.println("Substring before last separator = "+str.substring(0,sepPos));
}
}
Output
Substring before last separator = David
Advertisements