Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 682
Jack Avatar asked May 06 '26 01:05

Jack


2 Answers

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(...);
like image 196
camickr Avatar answered May 08 '26 15:05

camickr


String objects are immutable, you can't modify them after they've been created. Instead you will have to use StringBuilder to make a new one by appending the charAt().

like image 20
Clark Avatar answered May 08 '26 16:05

Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!