在Java中使用双引号连接字符串。

huangapple go评论124阅读模式
英文:

Concatenate String with double quotes in Java

问题

现在我有一个方法,它将返回XPath值,即:

  1. public String xpathValue(String countryName) {
  2. return "//*[@label=\"" + countryName + "\"]";
  3. }

如果我使用Nigeria调用它,它将返回以下值:

  1. //*[@label=Nigeria]

但我想要值用双引号括起来,就像这样:

  1. //*[@label="Nigeria"]

我该如何实现这个目标?

英文:

Now I have method, which will return me xpath value i.e.

  1. public String xpathValue (String countryName){
  2. return "//*[label="+countryName+"]"
  3. }

And if I call it with Nigeria it will return me value like this:

  1. //*[@label=Nigeria]

But I want value surrounded with double quotes, like this:

  1. //*[@label="Nigeria"]

How can I achieve this?

答案1

得分: 1

A valid xpath is:

  1. //*[@label='Nigeria']

and to generate the above, you can use the following line of code:

  1. return "//*[@label='" + countryName + "']";

and to generate:

  1. //*[@label="Nigeria"]

You can use the following line of code:

  1. return "//*[@label=\"" + countryName + "\"]";
  2. // ^the above backslash indicates that the following character i.e. \" is printable

POC

Code:

  1. public class XPathStringDemo {
  2. public static void main(String[] args) {
  3. XPathStringDemo obj = new XPathStringDemo();
  4. System.out.println(obj.xpathValue("Nigeria"));
  5. }
  6. public String xpathValue (String countryName){
  7. return "//*[@label=\"" + countryName + "\"]";
  8. }
  9. }

Output:

  1. //*[@label="Nigeria"]
英文:

A valid xpath is:

  1. //*[@label='Nigeria']

and to generate the above, you can use the following line of code:

  1. return "//*[@label='"+countryName+"']";

and to generate:

  1. //*[@label="Nigeria"]

You can use the following line of code:

  1. return "//*[@label=\""+countryName+"\"]";
  2. // ^the above backslash indicates that the following character i.e. " is printable

POC

Code:

  1. public class XPathStringDemo {
  2. public static void main(String[] args) {
  3. XPathStringDemo obj = new XPathStringDemo();
  4. System.out.println(obj.xpathValue("Nigeria"));
  5. }
  6. public String xpathValue (String countryName){
  7. return "//*[@label=\""+countryName+"\"]";
  8. }
  9. }

Output:

  1. //*[@label="Nigeria"]

huangapple
  • 本文由 发表于 2023年7月18日 06:54:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定