How to copy from a string to another string in Java?

Jack picture Jack · Apr 21, 2013 · Viewed 70k times · Source

I have two strings str1 and str2. I am trying to copy some letters from one string to the other by using charAt. I know that I can use string copy but I want some characters not all.

How can copy a subString from a string to another string in Java?

public class MyServerSide {

    public static void main(String[] args) {
        String str1 = "Hello World!;
        String str2;
        for (int 1=0; i < str1.length(); i++){
            if (i>=3){
                str2.charAt(i) = str1.charAt(i);//Here is the problem. It gives me an error
                                                //Saying that the left argument must be a 
                                                //variable

            }//End of if statement
        }//End of for loop
    }//End of main method
}//End of class

Answer

camickr picture camickr · Apr 21, 2013

Use String.substring(...) if you only want some characters.

Edit:

To combine an existing string with some characters from another string you would use:

String anotherString = anotherString + originalString.substring(...);

To create a new string with some characters from another string you would use:

String aNewString = originalString.substring(...);