如何解析一些字符后的字符

时间:2014-08-13 09:10:50

标签: java android

我有字符串H2SO4,例如,如何在O之后解析为int 4?我不能使用substring(4),因为用户可以输入例如NH3PO4,那里有4个子串(5),那么如何解析完全在O之后的任何字符?

感谢您的帮助。

8 个答案:

答案 0 :(得分:0)

将String转换为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)

答案 1 :(得分:0)

我认为您需要将String拆分为char数组&#39;然后搜索“&#39; o&#39;在那个数组中:

String str = "H2SO4"; 
char[] charArray = str.toCharArray();

然后你得到了:[H,2,S,O,4],你可以搜索&#34; O&#34;在这个数组中。

希望它有所帮助!

答案 2 :(得分:0)

你可以使用正则表达式。

      .*O([0-9]+).* 

并使用group来提取前进字符O.

在此处了解更多信息:

http://docs.oracle.com/javase/tutorial/essential/regex/groups.html

答案 3 :(得分:0)

有多种方式,所有方法都非常简单,取自Official documentation on String

//Find character index of O, and parse next character as int:
int index = str.indexOf("O");
Integer.parseInt(str.subString(index, index+1));

//loop trough char array and check each char
char[] arr = str.toCharArray();
for(char ch : arr){
    if(isNumber(ch){..}
}
boolean isNumber(char ch){
    //read below
}

参考ascii表和here

答案 4 :(得分:0)

为了在完全O之后解析每个字符,您可以使用以下代码:

char [] lettersArray = source.toCharArray();
for(int i =0 ;i<lettersArray.length;i++){
  if(Character.isLetter(lettersArray[i])){
      if(lettersArray[i]=='O'){
          try{
             int a = Interger.parseInteger(lettersArray[i].toString());
          }catch(Exception e){
              e.printStackTrace();
          }
      }
   }
}

答案 5 :(得分:0)

final int numAfterO;
final String strNum;
final int oIndex = chemicalName.lastIndexOf("O");
if (oIndex >= 0 && chemicalName.length() >= oIndex + 2) {
    strNum = chemicalName.subString(oIndex, oIndex + 1);
} else {
    strNum = null;
}
if (strNum != null) {
    try {
        numAfterO = Integer.parseInt(strNum);
    } catch (NumberFormatException e) {
        numAfter0 = -1;
    }
}
android.util.Log.d("MYAPP", "The number after the last O is " + numberAfterO);

我认为这就是你想要的。

答案 6 :(得分:0)

您的问题不明确,但这可能适合您的情况。

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");
    }
}

答案 7 :(得分:0)

这是解析整个分子结构的东西。这个解析整数&gt; 9也是。

public static class Molecule {
    private List<MoleculePart> parts = new ArrayList<MoleculePart>();

    public Molecule(String s) {
        String name = "";
        String amount = "";
        for (char c : s.toCharArray()) {
            if (inBetween(c, 'A', 'Z')) {
                if (!name.isEmpty()) // first iteration, the name is still empty. gotta omit.
                    save(name, amount);
                name = ""; 
                amount = "";
                name += c; //add it to the temporary name
            }
            else if (inBetween(c, 'a', 'z'))
                name += c; //if it's a lowercase letter, add it to the temporary name
            else if (inBetween(c, '0', '9'))
                amount += c;
        }
        save(name, amount);
    }

    public String toString() {
        String s = "";
        for (MoleculePart part : parts)
            s += part.toString();
        return s;
    }

    //add part to molecule structure after some parsing
    private void save(String tmpMoleculename, String amount) {
        MoleculePart part = new MoleculePart();
        part.amount = amount.isEmpty() ? 1 : Integer.parseInt(amount);
        part.element = Element.valueOf(tmpMoleculename);
        parts.add(part);
    }

    private static boolean inBetween(char c, char start, char end) {
        return (c >= start && c <= end);
    }
}

public static class MoleculePart {
    public Element element;
    public int amount;

    public String toString() {
        return element.name() + (amount > 1 ? amount : "");
    }
}

public static enum Element {
    O, S, H, C, Se, Ni //add as many as you like
}

public static void main(String[] args) {
    System.out.println(new Molecule("Ni84OH43Se"));
}