首页 > 其他分享 >Remove Beginning and Ending Double Quotes from a String

Remove Beginning and Ending Double Quotes from a String

时间:2022-08-26 07:55:17浏览次数:192  
标签:end String double Remove quotes Double input method

https://www.baeldung.com/java-remove-start-end-double-quote#:~:text=To%20remove%20double%20quotes%20just,be%20replaced%20by%20empty%20strings.

 

1. Overview

 

In this article, we're going to study different approaches for removing beginning and ending double quotes from a String in Java.

What we'll explore here can be useful for processing text extracted from files or received from other sources.

2. Simple Approach: the substring Method

 

Let's first start with a simple approach by using the substring method. This method can be called on a String object to return a specific sub-string.

The method requires two parameters:

  1. beginIndex — the index of the character where the sub-string should begin
  2. endIndex — the index after where the sub-string should end

Thus, considering that our input String is enclosed in double-quotes, we can use the substring method:


freestar
String input = "\"text wrapped in double quotes\"";
String result = input.substring(1, input.length() - 1);
System.out.println("Input: " + input);
System.out.println("Result: " + result);

By executing the code above, we have the following output:

Input: "text wrapped in double quotes"
Result: text wrapped in double quotes

When we are unsure whether the String will be enclosed in double-quotes or not, we should check it before running the substring method:

if (input != null && input.length() >= 2 
      && input.charAt(0) == '\"' && input.charAt(input.length() - 1) == '\"') {
    result = input.substring(1, input.length() - 1);
}

In the example above, we check that the String has at least two characters and that it starts and ends with double quotes.

3. Using the replaceAll Method

 

In addition to the substring method, we can also use the replaceAll method. This method replaces all parts of the String that match a given regular expression. Using replaceAll, we can remove all occurrences of double quotes by replacing them with empty strings:

String result = input.replaceAll("\"", "");

On one hand, this approach has the advantage of removing all occurrences of double quotes, even if the string has multiple lines. On the other hand, with this approach, we're unable to remove only the double quotes at the beginning and end of the String<iframe data-google-container-id="3" data-is-safeframe="true" data-load-complete="true" frameborder="0" height="250" id="google_ads_iframe_/15184186,7114245/baeldung_leaderboard_mid_2_0" marginheight="0" marginwidth="0" scrolling="no" src="https://b3685b8917ddc69f45820257baaa37dd.safeframe.googlesyndication.com/safeframe/1-0-38/html/container.html" title="3rd party ad content" width="970"></iframe>

freestar

To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression:

String result = input.replaceAll("^\"|\"$", "");

After executing this example, occurrences of double quotes at the beginning or at end of the String will be replaced by empty strings.

To understand this approach, let's break down our regular expression.

First, we have a caret symbol (^) followed by escaped double quotes (\”) for matching double quotes at the beginning of the String. Then, there is a pipe symbol (|) to indicate a matching alternative — similar to the OR logical operator.

Finally, we have escaped double quotes followed by a dollar symbol ($) for matching double quotes at the end of the String.

<iframe data-google-container-id="4" frameborder="0" height="250" id="google_ads_iframe_/15184186,7114245/baeldung_leaderboard_mid_3_0" marginheight="0" marginwidth="0" name="google_ads_iframe_/15184186,7114245/baeldung_leaderboard_mid_3_0" scrolling="no" title="3rd party ad content" width="300"></iframe> freestar

4. Using Guava

 

Another possible approach for removing double quotes from the beginning and end of a String is to use the CharMatcher class from the Guava library:

String result = CharMatcher.is('\"').trimFrom(input);

This approach is simpler to understand and removes only the beginning and end quotes from the String. However, for this approach to work, we need to add the guava library to our project:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>${guava-version}</version>
</dependency>

In this case, we need to set the ${guava-version} property to the version we want to use.

5. Conclusion

 

In this article, we explored different alternatives for removing double quotes at the beginning and at the end of a String. We can apply any of these approaches in practice. Each of them has advantages and disadvantages.

For example, when using the Guava library, we have a simple and elegant solution. However, in case Guava wasn't included in our project, this solution would require the addition of a new dependency.

As always, the code presented in this article is available over on GitHub.

标签:end,String,double,Remove,quotes,Double,input,method
From: https://www.cnblogs.com/kungfupanda/p/16626356.html

相关文章

  • [Oracle] LeetCode 415 Add Strings
    Giventwonon-negativeintegers,num1andnum2representedasstring,returnthesumofnum1andnum2asastring.Youmustsolvetheproblemwithoutusingany......
  • java的String.format中的百分号
    System.out.println(String.format("百分比%.2f%",(float)80/90));错误信息:Exceptioninthread"main"java.util.UnknownFormatConversionException:Conversion=......
  • Java 8 如何快速的将List<T>转换成List<Map<String,Object>>
    实际开发过程中,经常会遇到需要将List<T>转换List<Map<String,Object>>的情况,那么你们都是用什么方法实现的呢?下面是我开发过程中使用的方法,还望大佬看后轻喷。List<Map<......
  • StringBuilder类
    StringBuilder是字符串对象的缓冲区对象,缓冲区(出现目的,为了高效),提高String类的效率StringBuilder类的实现原理一个可变的字符序列,字符序列就是字符数组String......
  • Jedis操作string、Jedis操作hash
       Jedis操作stringJedls操作各种redis中的数据结构1)字符串类型stringsetget2)哈希类型hash:map格式hsethget3)列表类型list......
  • Object类和String类
    API的概念应用程序编程接口:每一个技术,官方都会定义出许多的功能,开发人员可以直接拿来使用(拿来主义).API可以理解为Sun公司已经开发好的类和方法.API文档就是我们......
  • String类型与基础类型的转换(String.valueof())
    1.由基本数据型态转换成String String类别中已经提供了将基本数据型态转换成String的static 方法 也就是String.valueOf()这个参数多载的方法 有下列几种 S......
  • 第十三章 StringTable
    翻篇是很重要的能力,从悲伤中大方走出来,就是艺术家1.String的基本特性String字符串定义的两种方式Strings1=“baidu”;//字面量的定义方式Strings2=newStr......
  • [Oracle] LeetCode 696 Count Binary Substrings
    Givenabinarystrings,returnthenumberofnon-emptysubstringsthathavethesamenumberof0'sand1's,andallthe0'sandallthe1'sinthesesubstring......
  • 记C# 通过JObject 读取 json对象(Newtonsoft.Json.Linq.JObject.this[string].get 返回
    json对象"RequestHeaders":{ "Host":"tool.kkbmtj.com", "Referer":"https://m.kkbmtj.com/ys/shortindex?origin=kktj&xcx", }代码:HeaderLogheaderLog......