[英]how to break a string into two parts in java
Let's assume a string consists of two parts, day and date.假设一个字符串由两部分组成,天和日期。
String arr[] = { "Tuesday 8/11/22", "Monday 15/3/21", "Friday 20/5/21" };
How can I only print out the latter part (date part) on console?我怎样才能在控制台上只打印出后半部分(日期部分)?
I recommend you use the date-time API instead of performing string manipulation of the elements.我建议您使用日期时间 API 而不是对元素执行字符串操作。 The string manipulation will not give you all the benefits that you can get by the specialized date-time API.字符串操作不会为您提供通过专门的日期时间 API 可以获得的所有好处。
You get your dates validated free of cost eg one of your dates, Friday 20/5/21
is incorrect.您可以免费验证您的日期,例如您的日期之一,2021 年 5 月 20 日Friday 20/5/21
不正确。 This date was Thursday and the java.time
API can perform this check for you automatically.这个日期是星期四, java.time
API 可以自动为您执行此检查。
Demo :演示:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
class Main {
public static void main(String[] args) {
String arr[] = { "Tuesday 8/11/22", "Monday 15/3/21", "Friday 20/5/21" };
DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEEE d/M/uu", Locale.ENGLISH);
for (String s : arr) {
LocalDate date = LocalDate.parse(s, parser);
// Now you can get individual units from date in a variety of ways
System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH));
System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.ENGLISH));
System.out.println(date.getYear());
// You can also format it in the desired ways
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/uu", Locale.ENGLISH);
String formatted = date.format(formatter);
System.out.println(formatted);
}
}
}
Output :输出:
Tuesday
Tue
2022
8/11/22
Monday
Mon
2021
15/3/21
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Friday 20/5/21' could not be parsed: Conflict found: Field DayOfWeek 4 differs from DayOfWeek 5 derived from 2021-05-20
at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2023)
Learn more about the modern Date-Time API from Trail: Date Time .从Trail 了解有关现代日期时间 API 的更多信息:日期时间。
As long as the day and date will stay in that format you can use the split()
function:只要日期和日期保持该格式,您就可以使用split()
函数:
class DateSplit {
public static void main(String[] args) {
String a = "Tuesday 8/11/22";
String[] result = a.split(" ");
System.out.println(result[1]);
}
}
where the delimiter splitting the string is the whitespace character.分隔字符串的分隔符是空白字符。
for(String str : arr) {
System.out.println(str.split(" ")[1])
}
public class Main {
public static void main(String[] args) {
String arr[] = { "Tuesday 8/11/22", "Monday 15/3/21", "Friday 20/5/21" };
for(int count = 0; count < arr.length; count++) {
String[] s = arr[count].split(" ");
System.out.println(s[1]);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.