从String中提取2个整数

时间:2013-03-20 14:04:20

标签: java string split integer substring

String weapon = "pistol . <1/10>";
Result:
int clip = 1;
int ammo = 1;

string =(WEAPON)的格式。 ≤(CLIP)/(AMMO)GT;
我需要Clip和Ammo值。

所以我如何提取String的这两个值。 我可以通过“/”拆分它仍将面对:“枪&lt; 1”和“10&gt;” 提前致谢

6 个答案:

答案 0 :(得分:7)

您可以删除这样的非数字字符:

String s = "pistol . <1/10>";
String[] numbers = s.replaceAll("^\\D+","").split("\\D+");

现在numbers[0]1numbers[1]10

  • s.replaceAll("^\\D+","")删除字符串开头的非数字字符,因此新字符串现在为"1/10>"
  • .split("\\D+")拆分非数字字符(在本例中为/>)并忽略尾随空字符串(如果有)

或者,如果格式总是与您在问题中提到的完全一致,那么您可以查找该特定模式:

private final static Pattern CLIP_AMMO = Pattern.compile(".*<(\\d+)/(\\d+)>.*");

String s = "pistol . <1/10>";
Matcher m = CLIP_AMMO.matcher(s);
if (m.matches()) {
    String clip = m.group(1); //1
    String ammo = m.group(2); //10
}

答案 1 :(得分:1)

String weapon = "pistol . <1/10>";

String str = weapon.substring(weapon.indexOf("<")+1,weapon.indexOf(">")); // str = "<1/10>"

int clip = Integer.parseInt(str.substring(0,str.indexOf("/"))); // clip = 1

int ammo = Integer.parseInt(str.substring(str.indexOf("/")+1)); // ammo = 10

clip = 1

ammo = 10

完成..

答案 2 :(得分:1)

你也可以尝试一下......

从字符串“(WEAPON)中提取值WEAPON,CLIP和AMMO。&lt;(CLIP)/(AMMO)&gt;”

String str = "(WEAPON) . <(CLIP)/(AMMO)>";
Pattern pattern = Pattern.compile("\\((.*?)\\)");
Matcher matcher = pattern.matcher(str);
while(matcher.find()) {
   System.out.println(matcher.group(1));
}

从字符串“手枪”中提取值1,10。&lt; 1/10&gt;“

List<String[]> numbers = new ArrayList<String[]>();
String str = "pistol . <1/10>";
Pattern pattern = Pattern.compile("\\<(.*?)\\>");
Matcher matcher = pattern.matcher(str);
while(matcher.find()) {
   numbers.add(matcher.group(1).split("/"));
}

答案 3 :(得分:1)

String weapon = "pistol . <1/10>";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(weapon); 
List<Integer> numbers = new ArrayList<Integer>();
while (m.find()) {
    numbers.add(Integer.parseInt(m.group()));
}
System.out.println("CLIP: " + numbers.get(0));
System.out.println("AMMO: " + numbers.get(1));

答案 4 :(得分:0)

然后你用“&lt;”分割得到的子串(枪&lt; 1)和“&gt;”分别为(10>)

答案 5 :(得分:0)

你可以尝试这样的事情。

public static void main(String[] args) {
    String weapon = "pistol . <1/10>";
    String test = "";

    Pattern pattern = Pattern.compile("<.*?>");
    Matcher matcher = pattern.matcher(weapon);

    if (matcher.find())
        test = matcher.group(0);

    test = test.replace("<", "").replace(">", "");
    String[] result = test.split("/");

    int clip = Integer.parseInt(result[0]);
    int ammo = Integer.parseInt(result[1]);
    System.out.println("Clip value is -->" + clip + "\n"
            + "Ammo value is -->" + ammo);
}

输出:

Clip value is -->1
Ammo value is -->10