简体   繁体   English

从字符串值中获取某些子字符串

[英]Get certain substring from a string value

I have the following dates: 我有以下日期:

"Friday, January 31",
"Wednesday, February 12",
"Monday, February 17",
"Wednesday, March 5",

I want to set up a string function where I am given the number always: 我想设置一个字符串函数,在此始终为我提供数字:

31
12
17
5

I started with this function: 我从此功能开始:

String strCheck = suspendedDates[i];
int pos = strCheck.length();
int pos2 = strCheck.indexOf(" ");

I am stuck right now, because how does it know which " " is it? 我现在陷入困境,因为它怎么知道是" "

Can someone help me with the function. 有人可以帮助我使用该功能吗?

use lastIndexOf() instead of indexOf() 使用lastIndexOf()代替indexOf()

final String str = "Friday, January 31";
System.out.println(str.substring(str.lastIndexOf(" ")));

Get the substring from the end. 从结尾获取子字符串。 Instead of trying to figure out locations 而不是试图找出位置

strCheck.substring(strCheck.length()-2);

This will take the last two characters. 这将占用最后两个字符。 Then just do a trim() in case it's a single character to remove the space:- 然后只是做一个trim() ,以防单个字符删除空格:-

strCheck.substring(strCheck.length()-2).trim();

Alternative 另类

The other option as mentioned is to do a lastIndexOf() on the String with a space (" ") as an argument which will search backward from the end of the String till it finds the space. 提到的另一个选项是对String进行lastIndexOf() ,并使用空格(“”)作为参数,该参数将从String的末尾向后搜索,直到找到空格为止。 But as the number can always be extracted in 2 character spaces, I see no reason to do 2 character compares every time you want to extract a known size String (2) in a known location ( length()-2 ) in order to retrieve the location that you already know. 但是由于可以始终在2个字符空间中提取数字,因此我认为没有理由每次要在已知位置( length()-2 )中提取已知大小的String (2)时都要进行2个字符比较。您已经知道的位置。

作为@JigarJoshi答案的替代方法,如果您不介意,可以使用正则表达式,删除所有非数字字符。

String result = dateString.replaceAll("[^\\d]+","");

I had to post it; 我不得不发布它; since this is a date I would go with Date parse to allow an additional check on the format of the inputs: 因为这是一个日期,所以我将使用Date解析来允许对输入格式进行额外检查:

An alternative way: 另一种方法:

SimpleDateFormat format = new SimpleDateFormat("EEEE, MMMM DD");
Calendar cal = Calendar.getInstance();

cal.setTime(format.parse("Friday, January 31"));
System.out.println(new SimpleDateFormat("DD").format(cal.getTime()));

2nd SimpleDateFormat("DD") is used instead of deprecated getDate() . 使用第二个SimpleDateFormat("DD")代替不推荐使用的getDate()

If you are trying to divide the string into parts for parsing, i suggest using String.split(" "), look at the javadocs and the internet for lots of nice examples of this in use! 如果您试图将字符串分成多个部分进行解析,我建议使用String.split(“”),请在javadocs和Internet上查找许多正在使用的漂亮示例! :) :)

You can use something like this: 您可以使用如下形式:

 String str = "Friday, January 31";
 Scanner s = new Scanner(s);
 s.useDelimiter( "\\D+" );
 while ( s.hasNextInt() ){
   s.nextInt(); // get int
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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