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);
}
}
}
标签:return,String,static,result,str,test,tmpStr
From: https://blog.51cto.com/u_16174476/6610413