
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 Substring After First Occurrence of a Separator in Java
We have the following string with a separator.
String str = "Tom-Hanks";
We want the substring after the first occurrence of the separator i.e.
Hanks
For that, first you need to get the index of the separator and then using the substring() method get, the substring after the separator.
String separator ="-"; int sepPos = str.indexOf(separator); System.out.println("Substring after separator = "+str.substring(sepPos + separator.length()));
The following is an example.
Example
public class Demo { public static void main(String[] args) { String str = "Tom-Hanks"; String separator ="-"; int sepPos = str.indexOf(separator); if (sepPos == -1) { System.out.println(""); } System.out.println("Substring after separator = "+str.substring(sepPos + separator.length())); } }
Output
Substring after separator = Hanks
Advertisements