如何在逗号之间删除字符串

时间:2016-03-27 08:28:57

标签: java string

例如,我有一个这样的字符串:

"香蕉,柠檬,橙,西瓜,..."

注意:我写...意味着更多数百种水果,它不属于上面的字符串。

所以我的问题是如何在第55个逗号和第56个逗号之间删除水果?

3 个答案:

答案 0 :(得分:2)

以下是使用String.split(...)和流的一种可能性。

public static String removeFruit(String fruits, int n)
{
  String[] a = fruits.split(",");
  return Stream.concat(Arrays.stream(a, 0, n), Arrays.stream(a, n + 1, a.length))
      .collect(Collectors.joining(","));
}

答案 1 :(得分:1)

String[] parts = string.split(",");
String fruit1=parts[0]
String fruit2=parts[1]
String fruit3=parts[2]

....等等。

答案 2 :(得分:0)

以下不是生产代码;你需要验证参数,它没有考虑要删除的水果可能是列表中的最后一个,等等。我相信你可以把它作为一个起点。

/** From fruits removes the item betwwen noth and (no + 1)th comma, 1-based */
private String removeItem(String fruits, int no) {
    int commaIx = -1; // imagine a 0th commas before the beginning of the string
    int previous = -2;
    for (int noComma = 0; noComma < no; noComma++) {
        previous = commaIx;
        commaIx = fruits.indexOf(',', commaIx);
        if (commaIx == -1) { // not found
            return fruits;
        }
    }
    return fruits.substring(0, previous + 1) + fruits.substring(commaIx + 1);
}
相关问题