如何从字符串中获取多个字符?
我正在尝试从数字列表中获取第五、第六和第七位数字。
例如,我想从变量dateofbirth
中获取年份,并将其保存为一个名为dob
的单独变量,作为int
。
这是我所拥有的:
int dateofbirth = 17031989
String s = Integer.toString(dateofbirth);
int dob = s.charAt(5);
我必须在 s.charAt
之后的括号中放入什么才能获得连续的几个数字?
I'm trying to get the 5th, 6th and 7th digits from a list of digits.
E.g. I want to get the year out of the variable dateofbirth
, and save it as a separate variable called dob
, as an int
.
Here is what I have:
int dateofbirth = 17031989
String s = Integer.toString(dateofbirth);
int dob = s.charAt(5);
What would I have to put in the parentheses after s.charAt
to get a few digits in a row?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
不需要字符串转换:
如果您确实想将其作为字符串进行转换,则 substring() 方法将是你的朋友。您还需要使用 Integer.parseInt() 将字符串转换回整数。将字符值作为整数将给出该字符的 ASCII 值,而不是表示该字符的整数!
No need for the string conversion:
If you did want to do it as a string, then the substring() method would be your friend. You'd also need to use
Integer.parseInt()
to convert the string back into an integer. Taking a character value as an integer will give you the ASCII value of that character, not an integer representing that character!s.substring(5)
将为您提供从索引5
开始的所有内容。您还可以给出第二个参数来指示您希望子字符串结束的位置。s.substring(5)
will give you everything starting from index5
. You could also give a second argument to indicate where you want the substring to end.您想要使用 String.substring(未经测试):
You want to use String.substring (untested):
如果您正在处理日期,您可以使用 SimpleDateFormat 和 Calendar 来提取年份:
If you are handling dates, you could use SimpleDateFormat and Calendar to pull out the year:
你做:
you do:
查看 String.substring() !
http://download.oracle .com/javase/6/docs/api/java/lang/String.html#substring%28int%29
Check out String.substring() !
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#substring%28int%29
这种方法不起作用有几个原因:
如果您想从此字符串中提取 1989,您应该使用 substring,然后使用 Integer.valueOf() 将此字符串转换为整数
This approach won't work for several reasons:
If you want to extract 1989 from this string you should use substring and then convert this string into an Integer using Integer.valueOf()
来自 JRE 文档:
getChars
From the JRE documentation:
getChars