简体   繁体   English

在java中将字符串的一部分转换为int

[英]converts parts of a string to int in java

I was wondering how can I take some numbers in a string and convert them to an integer type? 我想知道如何在字符串中取一些数字并将它们转换为整数类型? for example if a user entered 12:15pm how can I get 1 and 2 and make an int with value 12? 例如,如果用户在下午12:15输入,我如何得到1和2并使用值12进行int?

Given the example above, you could try something like this: 鉴于上面的例子,你可以尝试这样的事情:

final int value = Integer.parseInt(input.substring(0, input.indexOf(':'))); //value = 12

Where input = 12:15pm in this case. 在这种情况下, input = 12:15pm

Generally speaking, just use a combination of String#indexOf(String) , String#substring(int, int) and Integer.parseInt(String) . 一般来说,只需使用String#indexOf(String)String#substring(int, int)Integer.parseInt(String)

Read the String and Integer API's 阅读StringInteger API

  1. You can use the String.split() to get the two numeric strings 您可以使用String.split()来获取两个数字字符串
  2. You can use Integer.parseInt(...) to convert the String to an int. 您可以使用Integer.parseInt(...)将String转换为int。

Edit: Using the split() you can do something like: 编辑:使用split()可以执行以下操作:

String time = "12:34pm";
int hour = Integer.parseInt( time.split(":")[0] );

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

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