如果长度超过50,如何获取字符串?

时间:2013-09-10 10:21:29

标签: java string

在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);
                }
            }
        }

6 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:0)

尝试subString()indexOf()replace()

if(test.length() > 50)
        {
            System.out.println(test.substring(test.lastIndexOf(",") + 1, test.length()).replace(",", ""));
        }

答案 2 :(得分:0)

String someString = "";
    int lastCommaPosition = someString.lastIndexOf(",");
    if(lastCommaPosition > 50){
        String firstPart = someString.substring(0,lastCommaPosition +1);
        String secondPart = someString.substring(lastCommaPosition);
    }

答案 3 :(得分: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();
    }
}

答案 4 :(得分: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);

答案 5 :(得分: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;