Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all the characters after one character in the String?

Tags:

java

string

I have a String which contains a date, for example "01-01-2012", then an space and then the time "01:01:01". The complete string is: "01-01-2012 01:01:01"

I would like to extract only the date from this string so at the end I would have "01-01-2012" but don't know how to do this.

like image 577
Milos Cuculovic Avatar asked Feb 14 '12 12:02

Milos Cuculovic


People also ask

How do you remove all characters from a string after a specific character in Excel?

Type the formula: =LEFT(A2,FIND(“@”,A2)-1). Press the return key. This will give you the text obtained after removing everything following the '@' symbol from the string in cell A2.


1 Answers

Four options (last two added to make this one answer include the options given by others):

  • Parse the whole thing as a date/time and then just take the date part (Joda Time or SimpleDateFormat)
  • Find the first space using indexOf and get the leading substring using substring:

    int spaceIndex = text.indexOf(" ");
    if (spaceIndex != -1)
    {
        text = text.substring(0, spaceIndex);
    }
    
  • Trust that it's valid in the specified format, and that the first space will always be at index 10:

    text = text.substring(0, 10);
    
  • Split the string by spaces and then take the first result (seems needlessly inefficient to me, but it'll work...)

    text = text.split(" ")[0];
    

You should consider what you want to happen if there isn't a space, too. Does that mean the data was invalid to start with? Should you just continue with the whole string? It will depend on your situation.

Personally I would probably go with the first option - do you really want to parse "01-01-2012 wibble-wobble bad data" as if it were a valid date/time?

like image 70
Jon Skeet Avatar answered Oct 08 '22 23:10

Jon Skeet