54

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
  • Don't you mean, insert the string Jam to the end of Hello? Commented Sep 25, 2009 at 7:07
  • No, Hello to the beginning of Jam as _s be initialized with Jam Commented Sep 25, 2009 at 7:14

7 Answers 7

75

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;
Sign up to request clarification or add additional context in comments.

2 Comments

How do you know that this uses a StringBuilder behind the scenes ?
@MasterJoe: Read this question!
17

Other answers explain how to insert a string at the beginning of another String or StringBuilder (or StringBuffer).

However, strictly speaking, you cannot insert a string into the beginning of another one. Strings in Java are immutable1.

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 actually inserting characters into an existing String object at all.


1 - It is technically possible to use reflection to break abstraction on String objects and mutate them ... even though they are immutable by design. But it is a really bad idea to do this. Unless you know that a String object was created explicitly via new String(...) it could be shared, or it could share internal state with other String objects. Finally, the JVM spec clearly states that the behavior of code that uses reflection to change a final is undefined. Mutation of String objects is dangerous.

Comments

8

Sure, use StringBuilder.insert():

_sb.insert(0, _s);

Comments

0

You can add a string at the front of an already existing one. for example, if I have a name string name, I can add another string name2 by using:

name = name2 + name;

Don't know if this is helpful or not, but it works. No need to use a string builder.

1 Comment

OP asks about StringBuilder and a String -- that's what answers are supposed to address. Given that there are already quite good answers to this question, with the most upvoted also being the accepted one, it's advisable that new answers bring something in addition.
-1
private static void appendZeroAtStart() {
        String strObj = "11";
        int maxLegth = 5;

        StringBuilder sb = new StringBuilder(strObj);
        if (sb.length() <= maxLegth) {
            while (sb.length() < maxLegth) {
                sb.insert(0, '0');
            }
        } else {
            System.out.println("error");
        }

        System.out.println("result: " + sb);

    }

Comments

-7
import java.lang.StringBuilder;

public class Program {
    public static void main(String[] args) {

    // Create a new StringBuilder.
    StringBuilder builder = new StringBuilder();

    // Loop and append values.
    for (int i = 0; i < 5; i++) {
        builder.append("abc ");
    }
    // Convert to string.
    String result = builder.toString();

    // Print result.
    System.out.println(result);
    }
}

1 Comment

This does not answer the original post, it uses Strings and StringBuilder, but it does not "insert a string enclosed with double quotes in the beginning of the StringBuilding".
-13

It is better if you find quotation marks by using the indexof() method and then add a string behind that index.

string s="hai";
int s=s.indexof(""");

1 Comment

The string does not contain "

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.