-5

在java中如何拆分字符串值,如果>50,那么最后一个逗号之后的字符串应该分配给另一个字符串。

例如:

String test = "ASDFGHJKLPOIUYTRE YUIOOPPKMABJFD AJDJDJDJD, DJDJDJD DJDJDJ, JDJDJD UYUYUAU JKBFDKJBDKJJK";

上述字符串的长度为 88。在第 50 个字符 @59th "," 之后出现,因此字符串应与最后一个连续的 "逗号" 分割,输出应如下所示:

ASDFGHJKLPOIUYTRE YUIOOPPKMABJFD AJDJDJDJD, DJDJDJD DJDJDJ,

JDJDJD UYUYUAU JKBFDKJBDKJJK

提前致谢!!!

我试过如下:

if(add1.length() > 50){
            for(int i=50;i<add1.length();i++){
                if(add1.charAt(i)== ','){
                    add2 = add1.substring((i+1),add1.length());
                    add1 = add1.substring(0,i);
                }
            }
        }
4

6 回答 6

2

您可以使用字符串的indexOf方法来查找下一个逗号,然后手动拆分:

if(test.length() > 50){
    int comma = test.indexOf(',', 50);
    if(comma >= 0){

        //Bit before comma
        String partOne = test.substring(0, comma);

        //Bit after comma
        String partTwo = test.substring(comma);

        //Do Something
    }
}
于 2013-09-10T10:27:32.943 回答
0

尝试subString()indexOf()replace()

if(test.length() > 50)
        {
            System.out.println(test.substring(test.lastIndexOf(",") + 1, test.length()).replace(",", ""));
        }
于 2013-09-10T10:27:45.343 回答
0
String someString = "";
    int lastCommaPosition = someString.lastIndexOf(",");
    if(lastCommaPosition > 50){
        String firstPart = someString.substring(0,lastCommaPosition +1);
        String secondPart = someString.substring(lastCommaPosition);
    }
于 2013-09-10T10:29:47.917 回答
0
// Java version
public class StrSub {

    private String s = "ASDFGHJKLPOIUYTRE YUIOOPPKMABJFD AJDJDJDJD, DJDJDJD DJDJDJ, JDJDJD UYUYUAU JKBFDKJBDKJJK";

    private void compute() {
        int i = 50, p = 0, len = s.length();
        String s1, s2;
        for (i = 50; i < len; i++) {
            if (s.charAt(i) == ',') {
                p = i;
                break;
            }
        }
        System.out.println(p);
        s1 = s.substring(0, p+1);
        s2 = s.substring(p+1);

        System.out.println(s1);
        System.out.println(s2);
    }

    public static void main(String[] args) {
        StrSub s = new StrSub();        
        s.compute();
    }
}
于 2013-09-10T10:31:30.450 回答
0
String test = "ASDFGHJKLPOIUYTRE YUIOOPPKMABJFD AJDJDJDJD, DJDJDJD DJDJDJ, JDJDJD UYUYUAU JKBFDKJBDKJJK";
int index = 0;
if (test.length() > 50) {
    index = test.indexOf(",", 50);
}
String firstString = test.substring(0, index + 1);
String secondString = test.substring(index + 1);
System.out.println(firstString);
System.out.println(secondString);
于 2013-09-10T10:35:15.013 回答
0

试试这个...

int index = 0;
String[] out= new String[test.length()/50]();

for(int i=50, j=0; test.length() > 50 ; j++){

if(test.length>i){
      index = test.indexOf(",",i);
}
out[j] = test.subString(0,index);
test = test.subString(index+1, test.length());
}

// Cover the boundary condition
if(test.length() > 0){
out[j] = test;
于 2013-09-10T10:40:26.063 回答