拆分2个字符串并加入

时间:2014-12-20 08:10:39

标签: java android

我有2个字符串,我想按照我的要求加入。说我有

String sa = {"as,asd,asdf"};

  String qw = {"12,123,1234"};

  String[] separated = ItemSumm.split(",");

  String[] separateds = Itemumm.split(",");


     StringBuffer sb = new StringBuffer();
        for (int i = 0; i < separateds.length; i++)
        {
            if (separated.length == i + 1)
            {
                sb.append(separated[i] + "(" + separateds[i] + ")");
            } else
            {
                sb.append(separated[i] + "(" + separateds[i] + "),");
            }

        }
        deleteListItem.list_summ.setText(sb.toString());
  

它给出了(12),asd(123),asdf(1234)

但问题是,它可能就像

String sa = {"as,asdf"};

String qw = {"12,123,1234"};

所以在这里我想要

 as(12),asdf(123),1234

3 个答案:

答案 0 :(得分:0)

String sa = {"as,asd,asdf"};    
String qw = {"12,123,1234"};    
String[] separated = ItemSumm.split(",");    
String[] separateds = Itemumm.split(",");

StringBuffer sb = new StringBuffer();
// first loop through separated, starting with a comma
for (int i = 0; i < separated.length; i++) {
    sb.append(",").append(separated[i]).append("(").append(separateds[i]).append(")"));
}
// append remaining items in separateds
for (int i = separated.length; i < separateds.length; i++) {
    sb.append(",").append(separateds[i]);
}

deleteListItem.list_summ.setText(sb.toString().substring(1));  // remove starting comma

答案 1 :(得分:0)

如果字符串的长度是sa,则执行连接

if (separated.length == i + 1 && (separated[i].lenght == separateds[i].lenght))

答案 2 :(得分:0)

试试此代码:

    String sa = {"as,asd"};    
        String qw = {"12,123,1234"};    
        String[] separated = ItemSumm.split(",");    
        String[] separateds = Itemumm.split(",");

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < separateds.length; i++) {
            if (separated.length == i + 1) {
                if(separated.length == i) {
                    sb.append(separateds[i] + "");
                } else {
                    sb.append(separated[i] + "(" + separateds[i] + ")");
                }
            } else {
                if(separated.length == i) {
                    sb.append("," + separateds[i]);
                } else {
                    sb.append(separated[i] + "(" + separateds[i] + "),");
                }
            }
        }
deleteListItem.list_summ.setText(sb.toString());

//答案:as(12),asd(123),1234