I want to delete the colon in the string.

Asked 2 years ago, Updated 2 years ago, 30 views

I would like to delete only the colon(:) with the code below and put it in the new variable.What code would be best to use?

String beginTime="9:45";
String endTime = "19:45";

java

2022-09-30 15:33

2 Answers

Simply use String#replace(CharSequence,CharSequence).

beginTime.replace(":", "");

If you want to increase execution efficiency even a little, I think it's faster to use char[] by dividing the number of characters into four characters, but I don't think it's worth the trouble in practical use.


2022-09-30 15:33

I don't know if it's best, but
Example using StringBuilder:

public static void main(String argv[]){
    String beginTime = "9:45";
    String bt = deleteColon(beginTime);
    System.out.println(bt);
}
public static String deleteColon(String str) {
    StringBuilder sb = new StringBuilder(str);
    sb.deleteCharAt(sb.indexOf(":"));
    return sb.toString();
}


2022-09-30 15:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.