Home > other >  Can we remove unwanted delimiters from java
Can we remove unwanted delimiters from java

Time:09-17

I wanted that the program takes input removes the delimiters from that String then add it back then I can later parse it to a LocalDate object but I am not able to do the needful.

Scanner darshit = new Scanner(System.in);
String oo = "";
System.out.println("Enter your DOB: ");
String dob = darshit.next();
String[] words = dob.split("\\D");
for (int i = 0; i > words.length; i  ) {
    oo = oo   words[i];
}
System.out.println(oo);

After entering the DOB as 25-06-2008, for example, the output should be 25062008 or 2662008 but instead of this, I get a blank line!

CodePudding user response:

Use DateTimeFormatter to parse the input string to LocalDate and then format the LocalDate into a String of the desired format.

Demo:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner darshit = new Scanner(System.in);
        System.out.print("Enter your DOB: ");
        String dob = darshit.next();
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("dd[-][/]MM[-][/]uuuu", Locale.ENGLISH);

        LocalDate date = LocalDate.parse(dob, dtfInput);
        // Output in the default format i.e. LocalDate#toString implementation
        // System.out.println(date);

        // Output in a custom format
        DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("ddMMuuuu", Locale.ENGLISH);
        String formatted = dtfOutput.format(date);
        System.out.println(formatted);
    }
}

Notice the optional patterns in the square bracket which one of the great things about DateTimeFormatter.

A sample run:

Enter your DOB: 25-06-2008
25062008

Another sample run:

Enter your DOB: 25/06/2008
25062008

Learn more about the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8 APIs available through desugaring and How to use ThreeTenABP in Android Project.

CodePudding user response:

Can you just use Java Streams with the Collectors joining call ?

String value = Arrays.asList(dob.split("\\D")).stream().collect(Collectors.joining());

CodePudding user response:

String.replaceAll() and DateTimeFormatter

private static final DateTimeFormatter DATE_PARSER
        = DateTimeFormatter.ofPattern("[-]d-M-u[-]", Locale.ROOT);
private static final DateTimeFormatter DATE_FORMATTER
        = DateTimeFormatter.ofPattern("dd-MM-uuuu", Locale.ROOT);

public static void parseAndFormat(String input) {
    String adapted = input.replaceAll("\\W ", "-");
    System.out.println("Adapted input string: "   adapted);
    LocalDate date = LocalDate.parse(adapted, DATE_PARSER);
    String formatted = date.format(DATE_FORMATTER);
    System.out.println("Formatted:            "   formatted);
}

The above method parses your string:

    parseAndFormat("25-06-2008");

Output:

Adapted input string: 25-06-2008
Formatted:            25-06-2008

It’s very tolerant to which delimiters the users decides to use between the numbers, and also before or after them if any:

    parseAndFormat("$5///7  2008 ?");
Adapted input string: -5-7-2008-
Formatted:            05-07-2008

How it works: input.replaceAll("\\W ", "-") substitutes any run of non-word characters — everything but letters a through z and digits 0 through 9 — with a single hyphen. No one is interested in seeing the adapted input string, I am only printing it for you to understand the process better. The formatter I use for parsing accepts an optional hyphen first and last. The square brackets in the format pattern denote optional parts. It also accepts day and month in 1 or 2 digits and year in up to 9 digits. I use a separate formatter for formatting so I can control that day and month come in 2 digits and there are no hyphens before nor after.

CodePudding user response:

I myself found the solution

import java.util.Scanner;
import java.time.format.*;
import java.time.*;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter your DOB: ");
    String dateOfBirth = scanner.next();
    String dateOfBirth1 = dateOfBirth.replaceAll("\\s", "");
    String[] dateOfBirthArray = dateOfBirth1.split("[\\s\\-\\.\\'\\?\\,\\_\\@] ");
      int[] dateOfBirthArray1 = new int[dateOfBirthArray.length];
      for (int i = 0; i < dateOfBirthArray.length; i  ){
        dateOfBirthArray1[i] = Integer.parseInt(dateOfBirthArray[i]);
      }
      int dayDateOfBirth = dateOfBirthArray1[0] , monthDateOfBirth = dateOfBirthArray1[1];
      int yearDateOfBirth = dateOfBirthArray1[2];
      LocalDate today = LocalDate.now();
      LocalDate birthday = LocalDate.of(yearDateOfBirth, monthDateOfBirth, dayDateOfBirth);
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
      String birthday1 = birthday.format(formatter);
  }
}

According to me it is the easiest way and the public editors can edit the post for making it more clear

  • Related