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

72,889

Solution 1

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(...);

Solution 2

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().

Solution 3

charAt(int) method returns the character at specified index it doesn't set it, Use StringBuilder class and keep appending the characters that you want ignore others

Share:
72,889
Jack
Author by

Jack

Updated on July 26, 2020

Comments

  • Jack
    Jack almost 4 years

    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