例如,我有字符串H2SO4,如何在O之后解析到int 4?我不能使用子字符串(4),因为用户可以输入例如NH3PO4,并且有4的子字符串(5),那么我如何解析任何与O完全相同的字符呢?
谢谢你帮忙。
发布于 2014-08-13 09:26:22
你的问题还不清楚,但这可能对你的案子有用。
String str="NH3PO4";
int lastChar=str.lastIndexOf("O");//replace "O" into a param if needed
String toParse=str.substring(lastChar+1);
System.out.println("toParse="+toParse);
try{
System.out.println("after parse, " +Integer.parseInt(toParse));
}
catch (NumberFormatException ex){
System.out.println(toParse +" can not be parsed to int");
}
}发布于 2014-08-13 09:17:27
将字符串转换为char数组:
String molecule = "H2SO4 ";
char[] moleculeArray = str.toCharArray();
for(int i = 0; i < moleculeArray.length; i++){
if(Character.isLetter(moleculeArray[i])){
//Huston we have a character!
if(i+1 < moleculeArray.length && Character.isDigit(moleculeArray[i+1]) {
int digit = Character.getNumericValue(Character.isDigit(moleculeArray[i+1]);
//It has a digit do something extra!
}
}
}然后遍历数组并使用Character.isDigit(c)和Character.isLetter(c)
发布于 2014-08-13 09:17:50
我认为您需要将字符串拆分为char数组,然后在该数组中搜索'o‘:
String str = "H2SO4";
char[] charArray = str.toCharArray();然后得到: H,2,S,O,4,你可以在这个数组中搜索"O“。
希望能帮上忙!
https://stackoverflow.com/questions/25282312
复制相似问题