2
votes

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
9
Java Stings are not mutable, meaning that once their content is set, it can't be changed, instead, you should use String#subString or if you're really hooked on the idea of doing it yourself, StringBuilderMadProgrammer
Possible duplicate. This is already answered here. stackoverflow.com/questions/6952363/…hop
Thanks for all of your help guys.Jack

9 Answers

5
votes

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

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

2
votes

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

0
votes

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.

0
votes

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);
0
votes
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
votes

You can simply create a new instance using new operator.

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

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
            }
 }
-1
votes

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);
    }

}