java程序返回在参数String中找到的所有整数的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22551574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java program to return the sum of all integers found in the parameter String
提问by preeth
i want write a java program to return the sum of all integers found in the parameter String. for example take a string like:" 12 hi when 8 and 9" now the answer is 12+8+9=29. but i really dont know even how to start can any one help in this!
我想编写一个java程序来返回参数字符串中找到的所有整数的总和。例如,取这样的字符串:“12 hi when 8 and 9”现在答案是 12+8+9=29。但我真的不知道如何开始,任何人都可以帮助解决这个问题!
采纳答案by Baby
You may start with replacing all non-numbers from the string
with space
, and spilt
it based on the space
您可以从替换所有非数字开始string
使用space
,并且spilt
它的基础上的space
String str = "12 hi when 8 and 9";
str=str.replaceAll("[\D]+"," ");
String[] numbers=str.split(" ");
int sum = 0;
for(int i=0;i<numbers.length;i++){
try{
sum+=Integer.parseInt(numbers[i]);
}
catch( Exception e ) {
//Just in case, the element in the array is not parse-able into Integer, Ignore it
}
}
System.out.println("The sum is:"+sum);
回答by Sanjeev
You shall use Scanner to read your string
您应使用 Scanner 读取您的字符串
Scanner s = new Scanner(your string);
And then read it using
然后使用阅读它
s.nextInt();
Then add these integers.
然后将这些整数相加。
回答by barak manos
Here is the general algorithm:
下面是通用算法:
- Initialize your sum to zero.
- Split the string by spaces, and for each token:
- Try to convert the token into an integer.
- If no exception is thrown, then add the integer to your sum.
- 将您的总和初始化为零。
- 按空格分割字符串,并为每个标记:
- 尝试将令牌转换为整数。
- 如果没有抛出异常,则将整数添加到您的总和中。
And here is a coding example:
这是一个编码示例:
int sumString(String input)
{
int output = 0;
for (String token : input.split(" "))
{
try
{
output += Integer.parseInt(token);
}
catch (Exception error)
{
}
}
return output;
}
回答by anand mahuli
private static int getSumOfIntegersInString(String string) {
/*Split the String*/
String[] stringArray = string.split(" ");
int sum=0;
int temp=0;
for(int i=0;i<stringArray.length;i++){
try{
/*Convert the numbers in string to int*/
temp = Integer.parseInt(stringArray[i]);
sum += temp;
}catch(Exception e){
/*ignore*/
}
}
return sum;
}
回答by Salix alba
You could use a regular expression
你可以使用正则表达式
Pattern p = Pattern.compile("\d+");
String s = " 12 hi when 8 and 9" ;
Matcher m = p.matcher(s);
int start = 0;
int sum=0;
while(m.find(start)) {
String n = m.group();
sum += Integer.parseInt(n);
start = m.end();
}
System.out.println(sum);
This approach does not require the items to be separated by spaces so it would work with "12hiwhen8and9".
这种方法不需要用空格分隔项目,因此它可以与“12hiwhen8and9”一起使用。
回答by yellowB
Assume your words are separated by whitespace(s):
假设您的单词由空格分隔:
Then split your input string into "tokens"(continuous characters without whitespace). And then loop them, try to convert each of them into integer, if exception thrown, means this token doesn't represents a integer.
然后将您的输入字符串拆分为“令牌”(没有空格的连续字符)。然后循环它们,尝试将它们中的每一个转换为整数,如果抛出异常,则表示此标记不代表整数。
Code:
代码:
public static int summary(String s) {
String[] tokens = s.split("\s+");
int sum = 0;
for(String token : tokens) {
try {
int val = Integer.parseInt(token);
sum += val;
}
catch(NumberFormatException ne){
// Do nothing
}
}
return sum;
}
回答by java.mypassion
String s ="12 hi when 8 and 9";
s=s.replaceAll("[^0-9]+", " ");
String[] numbersArray= s.split(" ");
Integer sum = 0;
for(int i = 0 ; i<numbersArray.length;i++){
if(numbersArray[i].trim().length() != 0){
Integer value = Integer.valueOf(numbersArray[i].trim());
sum = sum + value;
}
}
System.out.println(sum);
回答by Chandan Mishra
You can have a look on the following code :-
您可以查看以下代码:-
public class Class02
{
public static void main(String[] args)
{
String str = "12 hi when 8 and 9";
int sum = 0;
List<String> list = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(str.toLowerCase());
while(st.hasMoreElements())
{
list.add(st.nextToken());
}
for(int i =0; i< list.size();i++)
{
char [] array = list.get(i).toCharArray();
int num = array[0];
if(!(num >= 'a' && num <= 'z'))
{
int number = Integer.valueOf((list.get(i).toString()));
sum = sum + number;
}
}
System.out.println(sum);
}
}
Hope it will help you.
希望它会帮助你。
回答by Kannan Ekanath
I understand that this does not have the Java8 tag but I will put this out there in case someone finds it interesting
我知道这没有 Java8 标签,但我会把它放在那里以防有人觉得它很有趣
String str = "12 hi when 8 and 9";
System.out.println(Arrays.stream(str.split(" "))
.filter(s -> s.matches("[0-9]+")).mapToInt(Integer::parseInt).sum());
would nicely print out 29
会很好地打印出 29