简体   繁体   English

拆分后如何获得正确的 substring?

[英]How to get the right substring after split?

I have a string like this: [name;24, name;23, name;22] .我有一个这样的字符串: [name;24, name;23, name;22] How can i split this string to obtain only the numbers after";"?如何拆分此字符串以仅获取“;”之后的数字?

String s = "[name ;24, name;23, name;22]";
String couples[] = s.replace("]", "").split(",");
int ages[] = new int[couples.length];
for (int i=0; i< couples.length; i++)
    ages[i] = Integer.parseInt(couples[i].split(";")[1]);
// Your input looks like this.
String s = "[name ;24, name;23, name;22]";

String[] numberStrings = s
    // First get rid of the known prefix and suffix
    .substring("[name ;".length(), s.length - "]".length())
    // Then split on the repeated portion that occurs between numbers.
    .split(", name;");

yet another method另一种方法

String str = "name ;24, name;23, name;22";
int p = 0;
while ((p  = str.indexOf(";", p + 1))  > -1) {
    System.out.println(str.substring(p+1).split("[^0-9]")[0]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM