Java 以逗号分割的字符串数据取出来,逗号前面的字符

时间:2025-02-16 10:30:03
/**
 * 取出逗号前面的字符
 */
public class Test {
    public static void main(String[] args) {
        String string = "1,2,3,4,5";
        //长度5 下标从0开始 到4
        String substring = string.substring(0, string.length()-1);
        //以逗号分割,得出的数据存到 result 里面
        String[] result = substring.split(",");
        for (String r : result) {
            System.out.println("分割结果是: " + r);
        }
    }
}

第二种截取后保留逗号

/***
 * 第一种截取
 */
@Test
public void TestString() {

    String st = ("2121,21,456,78900,1222");
    st += ',';
    int sz = 0;
    int index = 0;
    do {
        sz = index;
        index = st.indexOf(",", index + 1);
        if (index != -1) {
            System.out.println("结果" + st.substring(sz, index));
        }
    } while (index != -1);
}