Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将字符串转换为int求和,然后在必要时使用逗号返回字符串_Java_String_Int - Fatal编程技术网

Java 将字符串转换为int求和,然后在必要时使用逗号返回字符串

Java 将字符串转换为int求和,然后在必要时使用逗号返回字符串,java,string,int,Java,String,Int,我有一些用字符串表示的数字。其中一些文件的格式如下:“12309”。我需要将它们更改为整数,求和,然后在适当的位置将它们更改回带有逗号的字符串。我该怎么做呢?对以空格分隔的字符串使用正则表达式,这样就行了 String regex = "(?<=[\\d])(,)(?=[\\d])"; Pattern p = Pattern.compile(regex); String str = "12,000 1,000 42"; int currentInt = 0; int sum = 0;

我有一些用字符串表示的数字。其中一些文件的格式如下:“12309”。我需要将它们更改为整数,求和,然后在适当的位置将它们更改回带有逗号的字符串。我该怎么做呢?

对以空格分隔的字符串使用正则表达式,这样就行了

String regex = "(?<=[\\d])(,)(?=[\\d])";
Pattern p = Pattern.compile(regex);

String str = "12,000 1,000 42";

int currentInt = 0;
int sum = 0; 
String currentStr = "";

for(int i = 0; i < commaDelimitedNumbers.length; i++){

    currentStr = commaDelimitedNumbers[i];

    Matcher m = p.matcher(currentStr);

    currentStr = m.replaceAll("");

    currentInt = Integer.parseInt(currentStr);

    sum  += currentInt;
}

System.out.println(sum);
String regex=“(?使用类指定带逗号的格式。使用
parse
方法将
字符串
解析为
数字
,使用
format
方法将其转换回带逗号的
字符串


格式字符串“#,####”应足以表示逗号分隔的数字,如1234567。

看看这两个SO问题:[字符串到整数][1][整数到字符串][2][1]:[2]:我尝试过integer.valueOf()但这不起作用,因为它没有去掉逗号。我也尝试过使用NumberFormat,但我不确定它是如何工作的。@TGMCians,很好的观点(关于我删除的答案),其他人对此进行了更深入的讨论。为什么要使用patter/matcher?@giorashc,以防他在文件中的数字之间有其他字符。这是问题的最普遍解决方案。如果不匹配怎么办?您的解决方案不包括that@giorashc我对它进行了测试,即使没有匹配项,它也能正常工作ing不起作用吗?哦,天哪,我看错了你的模式。我的错误。这是适合这项工作的工具。OP应该看看。这是一个比我使用regex给出的更简洁的解决方案,谢谢你!