test



package com.ebay.test;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class StringUtil {

public static void main(String[] args) {

try {

int result = StringUtil.stringToInt("-1000.01");

System.out.println(result);

} catch (NumFmtException e) {

e.printStackTrace();

} catch (NumExcessException e) {

e.printStackTrace();

}

}

public static int stringToInt(String str) throws NumFmtException, NumExcessException {

int result = 0;

//preProcess string

String tmpStr = preProcess(str);

if (tmpStr.equals("")) {

return 0;

}

if(isLegalInt(tmpStr)) {

System.out.println("is legalInt");

result = process(tmpStr);

} else {

throw new NumFmtException("string must match ^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0|1-9]\\d*)$");

}

return result;

}

/**

* check if the string match regex

* @param str

* @return

*/

private static boolean isLegalInt(String str) {

Pattern p = Pattern

.compile("^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0|[1-9]\\d*)$");

Matcher m = p.matcher(str);

if (m.matches()) {

return true;

} else {

return false;

}

}

/**

* trim the string

*

* @param str

* @return

*/

private static String preProcess(String str) {

if(str == null) {

return "";

}

return str.trim();

}

private static int process(String str) throws NumExcessException {

//remove '.' and negative sign

boolean isNegative = false;

int result = 0;

String tmpStr = "";

if(str.contains(".")) {

tmpStr = str.substring(0, str.indexOf("."));

}

if (tmpStr.startsWith("-")) {

isNegative = true;

tmpStr = tmpStr.substring(1, tmpStr.length());

}

//convert to long first

char[] chs = tmpStr.toCharArray();

long l = 0l;

for (int i = chs.length-1, j =0; i >= 0; i--, j++) {

l += (chs[i]-'0') * Math.pow(10, j);

}

//check value range

if (l>Integer.MAX_VALUE) {

throw new NumExcessException("string is excess integer max value");

}

result = (int)l;

if (isNegative) {

result *= -1;

}

return result;

}

/**

* validate the string

*

* @param str

* @return

*/

private static boolean validate(String str) {

return true;

}

static class NumFmtException extends Exception {

public NumFmtException(String message) {

super(message);

}

}

static class NumExcessException extends Exception {

public NumExcessException(String message) {

super(message);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值