
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
Remove Leading and Trailing Quotes from a String in Java
In Java, handling strings with quotes can be managed by checking and manipulating the string's start and end. This example demonstrates how to remove double quotes from both the beginning and end of a string.
Problem Statement
Given a string enclosed in double quotes, write a Java program to remove these enclosing quotes. The result must be the original string without the enclosing double quotes.
Input
String with double quotes= "Demo Text"
Output
String after removing double quotes = Demo Text
Steps to remove the leading and trailing quotes from a string
Below are the steps to remove the leading and trailing quotes from a string ?
- Initialize the string.
- Remove beginning quote.
- If true, remove the first character using substring(1, originalStr.length()).
- Remove ending quote.
- If true, remove the last character using substring(0, originalStr.length() - 1).
- Print result.
Java program to remove the leading and trailing quotes from a string
public class Demo { public static void main(String[] args) { String originalStr =""Demo Text""; System.out.println("String with double quotes = " + originalStr); if (originalStr.startsWith(""")) { originalStr = originalStr.substring(1, originalStr.length()); } if (originalStr.endsWith(""")) { originalStr = originalStr.substring(0, originalStr.length() - 1); } System.out.println("String after removing double quotes = " + originalStr); } }
Output
String with double quotes= "Demo Text"
String after removing double quotes = Demo Text
Code Explanation
In this Java program, we remove the double quotes from the start and end of a string. We start with the string demo text enclosed in quotes. We first check if the string starts with a quote using if statement and remove it if true. Then, we check if the string ends with a quote and remove it if true. Finally, we print both the original and the modified strings. The output shows the original string with quotes and the modified string without them.