• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 304
  • Last Modified:

Java - Insrting double quotes into a string

I have a java String variable, and I want to concatenate double quotes to the beginning and end of the string like this:

String x = "SomeValue";

x = """" + x + """";

That is what I have tried, but it does not work.  When I am finished, the value of x should no longer be the literal string SomeValue, but SomeValue enclosed in double quotes.
0
jbaird123
Asked:
jbaird123
  • 6
  • 2
  • 2
2 Solutions
 
for_yanCommented:
String s = "abcd \" hjjh + \"" ;
0
 
for_yanCommented:
You ned to escape double qutes with backslash in front of it
0
 
for_yanCommented:

String x = "SomeValue";

x = "\"" + x + "\"";
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
for_yanCommented:
You can manipulate with double quotes in your strings if you add backslash immeditaely before the double quot - then
compile will not considet this double quote as a special symbol delimiting the string.
0
 
for_yanCommented:
This will look better:

String x = "SomeValue";

x = "\"" + x + "\""; 

Open in new window

0
 
for_yanCommented:
This is how it executes it in the test:

        String x = "SomeValue";

x = "\"" + x + "\"";

        System.out.println(x);

        

Open in new window


Output:

"SomeValue"

Open in new window

0
 
CEHJCommented:
Clearer and more efficient:
s = new StringBuilder().append('"').append(s).append('"').toString();

Open in new window

0
 
jbaird123Author Commented:
Perfect!  Thanks!
0
 
CEHJCommented:
??
0
 
jbaird123Author Commented:
Sorry, CEHJ,

I saw your comments after I awarded points.  I guess I was trying the solution and awarding points while you were submitting your answer.

The comment above was addressed to "for_yan".

0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 6
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now