views:

255

answers:

4

Hello All,

How to insert a string enclosed with double quotes in the beginning of the StringBuilder and String?

Eg:

StringBuilder _sb = new StringBuilder("Sam");

I need to insert the string "Hello" to the beginning of "Sam" and O/p is "Hello Sam".

String _s = "Jam";

I need to insert the string "Hello" to the beginning of "Jam" and O/p is "Hello Jam".

How to achieve this?

+2  A: 

Sure, use StringBuilder.insert():

_sb.insert(0, _s);
cletus
+4  A: 

The first case is done using the insert() method:

_sb.insert(0, "Hello ");

The latter case can be done using the overloaded + operator on Strings. This uses a StringBuilder behind the scenes:

String s2 = "Hello " + _s;
unwind
_s="Hello"+_s; will help to resolve the issue
Sri Kumar
@Sri: that's effectively what he said! If you think differently, then you are probably missing a fundamental property of Java Strings ... they are IMMUTABLE.
Stephen C
Opps! When i posted the comment i did not see unwind's edited answer that lead to the confusion :)
Sri Kumar
You can also use the String.concat() method. It can be a tad more efficient.
Sam Barnum
A: 

better u find " mark by using indexof() method..and to add string behind of that index string s="hai"; int s=s.indexof(""");..

maxy
That won't work as the " is not part of the String.
Joachim Sauer
+1  A: 

Strictly speaking, you cannot insert a string into the beginning of another one. Strings in Java are immutable.

When you write:

String s = "Jam";
s = "Hello " + s;

you are actually causing a new String object to be created that is the concatenation of "Hello " and "Jam". You are not inserting characters into an existing String object at all.

Stephen C