0

I have string H2SO4 for example, how can i parse to int 4 after O? I can't use substring(4), because user can type for example NH3PO4 and there 4 is substring(5), so how can I parse any character that is exactly after O?

Thanks for help.

8 Answers8

0

Convert the String to a char array:

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!
        }
    }
}

then iterate over the array and use Character.isDigit(c) and Character.isLetter(c)

Rawa
  • 13,357
  • 6
  • 39
  • 55
0

I think you need to split your String to char array' and then search the 'o' in that array:

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

Then you got : [H, 2, S, O, 4], and you can search the "O" in this array.

Hope it helped!

Itay
  • 219
  • 5
  • 14
0

you can use regular expression.

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

And use group to extract the number proceeding character O.

Find out more here:

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

40pro
  • 1,283
  • 2
  • 15
  • 23
0

There are multiple ways, all of them very simple and taken from 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
}

refer to ascii table and here

Community
  • 1
  • 1
Marius
  • 810
  • 7
  • 20
0

In order to parse every character after exactly O you can use the follow code:

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();
          }
      }
   }
}
Rawa
  • 13,357
  • 6
  • 39
  • 55
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);

I assume this is what you want.

Eric Cochran
  • 8,414
  • 5
  • 50
  • 91
0

Your question is not clear, but this may work for your case.

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");
    }
}
JaskeyLam
  • 15,405
  • 21
  • 114
  • 149
0

Here's something that parses an entire molecule structure. This one parses integers > 9 as well.

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"));
}
stealthjong
  • 10,858
  • 13
  • 45
  • 84