从字符串中提取整数

huangapple go评论93阅读模式
英文:

Extracting integer from a string

问题

你好,我刚开始学习Java,遇到了一个问题。

问题的描述是,如果我们有一个字符串 S:

S = "123:456:789"

我们需要分别提取出数字 123、456 和 789,并将它们存储在不同的变量中,例如:

int a = 123;
int b = 456;
int c = 789;

我们应该如何做到这一点呢?

英文:

Hi I am just starting to learn java and i am stuck on a problem.
The problem states that if we have a string S

S = "123:456:789"

We have to extract the numbers 123 ,456,789 separately and store them in different variables such as

int a=123
Int b=456
Int c=789

How can we do that?

答案1

得分: 1

可以通过:字符将它们分割,然后解析这些字符串并按如下方式保存到数组中:

String S = "123:456:789";
String[] arr = S.split(":");
int[] integers = new int[arr.length];
for(int i = 0; i < arr.length; i++) 
     integers[i] = Integer.parseInt(arr[i]);
英文:

You can split them by the : character and then save parse the Strings and save them in an array as follows:

String S = &quot;123:456:789&quot;;
String[] arr = S.split(&quot;:&quot;);
int[] integers = new int[arr.length];
for(int i = 0; i &lt; arr.length; i++) 
     integers[i] = Integer.parseInt(arr[i]);

答案2

得分: 0

你可以根据分隔符将字符串分割成字符串数组。一旦你有了字符串数组,就可以访问每个数组元素以获取特定的值。

String S = "123:456:789";
String[] example = S.split(":");

来源:https://javarevisited.blogspot.com/2017/01/how-to-split-string-based-on-delimiter-in-java.html

英文:

You can split the string based on a delimiter into a string array. Once you have the string array you can access each array's element to get the specific values.

String S = &quot;123:456:789&quot;
String[] example = S.split(&quot;:&quot;);

Source: https://javarevisited.blogspot.com/2017/01/how-to-split-string-based-on-delimiter-in-java.html

答案3

得分: 0

查看String中的split()方法,以及Integer.parseInt()方法。
你还需要查阅正则表达式。1

英文:

Look at the method split() in String, and into Integer.parseInt().
You also need to look into Regular Expressions

huangapple
  • 本文由 发表于 2020年4月8日 03:52:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/61088316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定