今上午写的一个程序需要将字符串10^8转换成double型数值,于是想到通过^作为分隔符,得到底数10和指数8,再调用Math.pow(a, b)函数来完成这一转换操作。
但是"10^8".split("^");出错。
后来在网上看到split函数的参数是正则表达式,而^,|,$,\,*,+,-,?等都是其特殊字符。因此,使用时需要加\\进行转义。
/**
* Copyright (c) 2011 Trusted Software and Mobile Computing(TSMC)
* All rights reserved.
* Author: Jarg Yee <yeshaoting@gmail.com>
* http://jarg.iteye.com/
*/
/*
* ^分隔字符串
*/
public class Test
{
public static void main(String[] args)
{
String R = "10^8"; //待分隔的字符串
String[] RStr = R.split("\\^"); //以^为分隔符,分隔字符串
double a = Double.parseDouble(RStr[0]);
double b = Double.parseDouble(RStr[1]);
System.out.println(Math.pow(a, b)/10);
}
}
---------- 运行Java ----------
1.0E7
输出完成 (耗时 0 秒) - 正常终止