- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Get the substring after the first occurrence of a separator in Java
- Get the last occurrence of a substring within a string in Arduino
- Get the index of the first occurrence of a separator in Java
- How to get everything before the last occurrence of a character in MySQL?
- Get the first occurrence of a substring within a string in Arduino
- How to find index of last occurrence of a substring in a string in Python?
- Finding the last occurrence of a character in a String in Java
- Get the index of last substring in a given string in MySQL?
- How to find the last occurrence of an element in a Java List?
- How to get the last index of an occurrence of the specified value in a string in JavaScript?
- Get left part of the string on the basis of last occurrence of delimiter in MySQL?
- How to update a value with substring of current value by removing the separator and numbers after a separator in MySQL?
- How to find the nth occurrence of substring in a string in Python?
- Get the last day of month in Java
- MySQL query to get a substring from a string except the last three characters?

Advertisements