How can I do it faster in java? Copy chars of a long string

Viewed 33

I have a text file: (CNC G-code) Number of lines: 14415 Number of chars: 263950

I have to change some tool command in it. If I find "T***", for example "T120", I need to replace it for an other tool command, given by user, for example "T30".

I writed a working program (javafx), read txt file, change tools, export txt file, but the change method is really slow.

That is how it works now, in a simple form, I copy every char to an other string variable, except if I need to replace:

String originalGcode come from txt file reading
String newGcode = "";

for ( int i = 0; i < originalGcode.length(); i++ ){
   if ( condition == true ){
       newGcode += newToolCodeFromUser;
   } else {
       newGcode += originalGcode.charAt(i);
}

Now it takes 34 second. Do you have any idea, how to do it under 1-2 second?

Replace is not a good solution, because: - I have many of tool code in the G-code - One tool code (forexample T120) appears many times. - For example: I have T120 in line 20 and line 30 and T30 in line 50 and line 60 in the program - First, user wants to change T120 to T30 - Second, user wants to change T30 to T77 -> I have to replace T30 only in line 50 and 60, but I have already T30 in line 20 and 30 because of the first change command.

I am new at programming JAVA, please explain your solution :)

1 Answers

Assuming there does not exist a cycle in the replacement logic, you might be able to just do a series of replacements:

String originalGcode = "T10 T30 T120 T20";
String newGcode = originalGcode.replace("T30", "T77")
    .replace("T120", "T30");
System.out.println(newGcode);

This prints:

T10 T77 T30 T20
Related