2

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
cello
  • 5,356
  • 3
  • 23
  • 28
Jack
  • 258
  • 2
  • 7
  • 15
  • 1
    Java Stings are not mutable, meaning that once their content is set, it can't be changed, instead, you should use [String#subString](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)) or if you're really hooked on the idea of doing it yourself, [StringBuilder](http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html) – MadProgrammer Apr 21 '13 at 03:54
  • Possible duplicate. This is already answered here. http://stackoverflow.com/questions/6952363/java-replace-a-character-at-a-specific-index-in-a-string – hop Apr 21 '13 at 03:57
  • possible duplicate of [How should I copy Strings in Java?](http://stackoverflow.com/questions/10607990/how-should-i-copy-strings-in-java) – james.garriss Feb 12 '15 at 15:52

9 Answers9

5

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(...);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • I am not sure if I get it. How can I copy from a string to another? Do I have to do it like this; str1.substring(0,3)=str2.substring(0,3) ? – Jack Apr 21 '13 at 04:08
4

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

Clark
  • 1,357
  • 1
  • 7
  • 18
2

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

jmj
  • 237,923
  • 42
  • 401
  • 438
0

str2.charAt(i) function returns a value; it does not allow to set the character at that position - hence it says the left part should be a variable.

shiladitya
  • 2,290
  • 1
  • 23
  • 36
0

You can convert both the two strings in two char arrays and work on them. on the end of your algorithm recreate the str2 from the second char array:

char[] ch1 = str1.toCharArray();
char[] ch2 = str2.toCharArray();

for (int i=0; i < ch1.length; i++)
    if (i>=3)
        ch2[i] = ch1[i];

str2 = new String(ch2);
Salvi94
  • 9
  • 2
0
import java.sql.*;
import java.io.*;
import javax.sql.*;
class Ems 
{
public static void main(String args[])
{
        int ch;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =DriverManager.getConnection("jdbc:oracle:thin:@finn:1521:orcl","hr","hr");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from EmpDirc");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4)+" "+rs.getString(5)
+" "+rs.getString(6)+" "+rs.getString(7));

            do
            {
                System.out.println("\n");
                System.out.println("              ENTER EMPLOYEE DETAILS:");
                System.out.println("1.Insert Record into the Table");
                System.out.println("2.Update The Existing Record.");
                System.out.println("3.CALCULATE PRIVILAGE LEAVE");
                System.out.println("4.Display all the Records from the Table");
                System.out.println("5.Exit");
                System.out.println("Enter your choice: ");



                System.out.println("4.Exit");
                System.out.println("Enter your choice: ");

                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                ch=Integer.parseInt(br.readLine());

                  switch(ch)
                {
                    case 1:

                System.out.println("1.INSERT EMPLOYEE ID.");
                int num= Integer.parseInt(br.readLine());
                System.out.println("2.INSERT EMPLOYEE NAME");
                String ename=br.readLine();
                System.out.println("3.INSERT EMPLOYEE DESIGNATION");
                String desig=br.readLine();
                System.out.println("4.INSERT EMPLOYEE DATEOFBIRTH");
                String dob=br.readLine();
                System.out.println("5.INSERT EMPLOYEE PHONE NO OR ANY CONTACT");
                String mob= br.readLine();
                System.out.println("6.INSERT EMPLOYEE EMAIL ID");
                String email= br.readLine();
                System.out.println("7.INSERT EMPLOYEE SALARY");
                String sal=br.readLine();
                System.out.println("8.INSERT EMPLOYEE paid LEAVES");
                String pl=br.readLine();
                System.out.println("9.INSERT EMPLOYEE CASUAL LEAVES");
                String cl=br.readLine();
                System.out.println("10.INSERT EMPLOYEE FINAL SALARY");
                String fi= br.readLine();


                    String sql="insert into EmpDirc values(?,?,?,?,?,?,?,?,?,?)";
                    PreparedStatement p=con.prepareStatement(sql);
                    p.setInt(1,num);
                    p.setString(2,ename);
                    p.setString(3,desig);
                    p.setString(4,dob);
                    p.setString(5,mob);
                    p.setString(6,email);
                    p.setString(7,sal);
                    p.setString(8,pl);
                    p.setString(9,cl);
                    p.setString(10,fi);


                    p.executeUpdate();
                    System.out.println("Record Added");
                    //p.close();
                    //con.close();
                    break;


            case 2:
                    System.out.println("UPDATE EMPLOYEE id : ");
                    int emnum=Integer.parseInt(br.readLine());
            System.out.println("UPDATE EMPLOYEE DESIGNATION : ");
                    String emdesig=br.readLine();
                    System.out.println("UPDATE EMPLOYEE PHONE: ");
                    String emphn=br.readLine();
                    System.out.println("UPDATE EMPLOYEE EMAIL: ");
                    String emmail=br.readLine();
                    System.out.println("UPDATE EMPLOYEE SALARY: ");
                    String emsal=br.readLine();
                    System.out.println("UPDATE EMPLOYEE PL: ");
                    String empl=br.readLine();
                    System.out.println("UPDATE EMPLOYEE CL: ");
                    String emcl=br.readLine();
                    System.out.println("UPDATE EMPLOYEE FINAL SALARY: ");
                    String emfi=br.readLine();
                    sql="update EmpDirc set Desig=?, Phnum=? , Email=?, Salary=? , Pl=?, Cl=?, TakeHomeSal=? where Empid=?";
                    PreparedStatement  ps=con.prepareStatement(sql);

                    ps.setString(1,emdesig);
                    ps.setString(2,emphn);
                    ps.setString(3,emmail);
                    ps.setString(4,emsal);
                    ps.setString(5,empl);
                    ps.setString(6,emcl);
                    ps.setString(7,emfi);
            ps.setInt(8,emnum);
                    ps.executeUpdate();
                    System.out.println("Record Updated");
                    //p.close();
                    //con.close();
                    break;


                    case 3:
                    System.exit(0);

                    default:
                    System.out.println("Invalid Choice");
                    break;
}
}while(ch!=2);


con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
0

You can simply create a new instance using new operator.

String str1 = "abc";
String str2 = new String(str1);
0

See below code it will work first initialize str2

public static void main(String[] args) {
    String str1 = "Hello World!;
            String str2="";//Here initialize first
            for (int 1=0; i < str1.length(); i++){
                if (i>=3){
                   str2 = str2+str1.charAt(i);//Concatenate existing string with new String
                }//End of if statement
            }
 }
Mohammad Sommakia
  • 1,773
  • 3
  • 15
  • 48
Prince
  • 1
  • 2
-1

Since Strings are immutable you will end up in error if you try to copy just by using the assignment operator as you stated above.Instead you can append each Character with the existing one like the code below:

class Cpystring{
    public static void main(String args[])
   {
       String str1="Hello World";
       String str2="";
      for(int i=0;i<str1.length();i++)
      {
          str2+=str1.charAt(i);
       }
       System.out.println(str2);
    }

}

  • Welcome to Stack Overflow! This does not really answer the question. While your "immutable string" argument is true the root cause of the OPs problem is a wrong syntax. – Timothy Truckle Jan 15 '17 at 12:23