简体   繁体   中英

Remove last characters from string

I have a long string dates that I receive from an API call and they are returned as

Event Name 2017-03-23T10:00.000+01:00

How do I trim it so that I can remove the characters from all of the events that I get back and be left with only

Event Name 2017-03-23 10:00

How do I trim it so that I can remove the characters from all of the events that I get back and be left with only

Event Name 2017-03-23 10:00

Try this:

String str = "Event Name 2017-03-23T10:00.000+01:00";
String newString = str.replace("T"," ");
System.out.println(newString.substring(0, newString.lastIndexOf(".")));

result is --> Event Name 2017-03-23 10:00

side note - as you can see working with Strings is a bit inefficient in terms of constructing a new object each time, you may consider looking into StringBuilder . However, if you're doing no more operations then I've already done then that should be fine.

EDIT

Alternative solution

String str = "Event Name 2017-03-23T10:00.000+01:00";
System.out.println(str.split("\\.")[0]);

Note - this is similar to the solution above but leaves the "T" where it currently is. you can then go on further and do what you wish to do with it.

StringBuilder sb = new StringBuilder("Event Name 2017-03-23T10:00.000+01:00");
sb.setLength(27);
System.out.println(sb.toString());
     if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
            str = str.substring(0, str.length() - 1);
     }

Change x with your last character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM