英文:
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 = "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]);
答案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 = "123:456:789"
String[] example = S.split(":");
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论