Remove extra delimiter from a String in Java
Given a String with extra delimiter at the end, the task is to remove this extra delimiter in Java.
Examples:
Input: String = "Geeks, For, Geeks, ", delimiter = ', ' Output: "Geeks, For, Geeks" Input: String = "G.e.e.k.s.", delimiter = '.' Output: "G.e.e.k.s"
Approach:
- Get the String.
- Get the last index of the delimiter using lastIndexOf() method.
- Construct a new String with the 2 different substrings: one from beginning till the found index – 1, and the other from the index + 1 till the end.
Below is the implementation of the above approach:
// Java program to remove// extra delimiter at the end of a StringpublicclassGFG {publicstaticvoidmain(String args[]){// Get the StringString str ="Geeks, For, Geeks,";// Get the delimiterchardelimiter =',';// Print the original stringSystem.out.println("Original String: "+ str);// Get the index of delimiterintindex = str.lastIndexOf(delimiter);// Remove the extra delimiter by skipping itstr = str.substring(0, index)+ str.substring(index +1);// Print the new StringSystem.out.println("String with extra "+"delimiter removed: "+ str);}}chevron_rightfilter_noneOutput:Original String: Geeks, For, Geeks, String with extra delimiter removed: Geeks, For, Geeks
Recommended Posts:
- Scanner delimiter() method in Java with Examples
- Remove all non-alphabetical characters of a String in Java
- How to remove all white spaces from a String in Java?
- Remove Leading Zeros From String in Java
- Trim (Remove leading and trailing spaces) a string in Java
- Remove a given word from a String
- HashSet remove() Method in Java
- Set remove() method in Java with Examples
- ArrayBlockingQueue remove() method in Java
- LinkedList remove() Method in Java
- How to remove a SubList from a List in Java
- Stack remove(int) method in Java with Example
- IdentityHashMap remove() Method in Java
- How to Remove Duplicates from ArrayList in Java
- ArrayDeque remove() Method in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



