-3

I have the code:

String str="Date-01-2017"

How can I print 2017 only from this string?

I don't know how to split and get the return as 2017.

Artem Mostyaev
  • 3,874
  • 10
  • 53
  • 60
  • 1
    Split by dash (`-`) and then get the third element of the array, like this: `str.split("-")[2]` – Piyin Dec 01 '17 at 14:39

4 Answers4

0

You can try:

String[] splitString = dateString.split("-");
String year = splitString[2];
mdrafiqulrabin
  • 1,657
  • 5
  • 28
  • 38
0

You can use substring method to take the part of the string you need:

String data = "Date-01-2017";
String year = data.substring(data.length() - 4, data.length());
David SN
  • 3,389
  • 1
  • 17
  • 21
0

You could use regular expression:

Pattern pattern = Pattern.compile("\\w+-(?<month>\\d{2})-(?<year>\\d{4})");
Matcher matcher = pattern.matcher("Date-01-2017");

if(matcher.matches())
    System.out.println(matcher.group("year"));
else
    System.out.println("NOT MATCH!!!");

demo

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

Another way to print if the string "2017" is using a function, such as this.

public boolean contains(CharSequence s) {
        return indexOf(s.toString()) > -1;
    }

You can make a call to this function, with the string as the parameter, and if the string contains 2017, then u can print out that string.

  • 1
    I think OP wanted to print the string "2017", not *if* the string contains it or not. – eis Dec 02 '17 at 13:12