String str="33 and P090204 my salary is ¥8400.4 ";
提取所有数值进行相加33+90204+8400.4=98637.4返回。
这个程序怎么写
[b]问题补充:[/b]
不用替换这样方法
但还是谢谢你
[b]问题补充:[/b]
对字符串硬处理
请教各位一道题目
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- rednaxelafx 2009-03-05 19:26关注
[quote="abcbbc"]问题补充:
不用替换这样方法
对字符串硬处理[/quote]
呃……嗯?不过我上面的办法没用到替换啊。这处理方式已经很硬了……[code="java"]import java.io.*;
public class Test {
private static double nextDouble(Reader in) throws IOException {
int c = -1;
while (!Character.isDigit(c = in.read()) && -1 != c) { }
if (-1 == c) return Double.NaN;StringBuilder sb = new StringBuilder(Character.toString((char)c)); while (Character.isDigit(c = in.read())) { sb.append((char)c); } if ('.' == (char)c) { sb.append('.'); while (Character.isDigit(c = in.read())) { sb.append((char)c); } } return Double.parseDouble(sb.toString()); } public static void main(String[] args) throws Exception { String str = "33 and P090204 my salary is ¥8400.4 "; double acc = 0; double d = 0; StringReader in = new StringReader(str); while (!Double.isNaN(d = nextDouble(in))) { acc += d; } System.out.println(acc); // 98637.4 }
}[/code]
那或许你想要的是这样?
再不行的话就把Character.isDigit()换成:
[code="java"]private static boolean isDigit(int codePoint) {
return codePoint >= '0' && codePoint <= '9';
}[/code]
然后把Double.parseDouble()也换成自己的实现……hmm本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报