Java - 按编号和字母拆分字符串 [英] Java - Split String by Number and Letters
问题描述
所以我有一个字符串,比如这个 C3H20IO
So I have, for example, a string such as this C3H20IO
我想做的就是拆分这个字符串所以我得到以下内容:
What I wanna do is split this string so I get the following:
Array1 = {C,H,I,O}
Array2 = {3,20,1,1}
1
作为 Array2
的第三个元素表示 I
元素的单原子性质。 O
也是如此。这实际上是我正在努力的部分。
The 1
as the third element of the Array2
is indicative of the monoatomic nature of the I
element. Same for O
. That is actually the part I am struggling with.
这是一个化学方程式,所以我需要根据它们的名称和原子数等来分离元素。 。
This is a chemical equation, so I need to separate the elements according to their names and the amount of atoms there are etc.
推荐答案
您可以尝试这种方法:
String formula = "C3H20IO";
//insert "1" in atom-atom boundry
formula = formula.replaceAll("(?<=[A-Z])(?=[A-Z])|(?<=[a-z])(?=[A-Z])|(?<=\\D)$", "1");
//split at letter-digit or digit-letter boundry
String regex = "(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)";
String[] atoms = formula.split(regex);
输出:
原子:[C,3,H,20,I,1,O,1]
atoms: [C, 3, H, 20, I, 1, O, 1]
现在所有偶数指数均匀(0,2,4 ......)是原子,奇数是相关的数字:
Now all even even indices (0, 2, 4...) are atoms and odd ones are the associated number:
String[] a = new String[ atoms.length/2 ];
int[] n = new int[ atoms.length/2 ];
for(int i = 0 ; i < a.length ; i++) {
a[i] = atoms[i*2];
n[i] = Integer.parseInt(atoms[i*2+1]);
}
输出:
a:[C,H,I,O]
n:[3,20,1,1]
a: [C, H, I, O]
n: [3, 20, 1, 1]
这篇关于Java - 按编号和字母拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!