如何按顺序计算字符串中的字符?

How to count characters in order in a String?

我有一个 String 用于 2D 平台游戏的编辑器,用户可以在其中单击 16x60 矩形板来创建自定义板。我遍历这些矩形并得到一个我想要 trim 的字符串。 x 是块,a 是空的 space。我需要这个来绘制关卡。

String s = "x1x1x1x1a1a1x1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1";

我想trim这个到x4a2x1a54。基本上是将紧接着出现的 x 和 a 相加。

我该怎么做?

特此通知您,Whosebug 不是获取代码的论坛,而是帮助您处理代码并指出错误或提出建议的论坛。

我很不喜欢一个需求,但由于这个问题让我有点头疼,这里是我的版本。不幸的是,我不能只使用 Streams 并且不得不向它添加一个 Arraylist(也许使用流的 reduce 和 collect 方法可以在一行中实现)但它按预期工作。

    String s = "x1x1x1x1a1a1x1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1";
    ArrayList<String[]> map = new ArrayList<>();
    for(String c:s.split("(?<=\G..)")){
        if(map.isEmpty()||!map.get(map.size()-1)[0].equals(c.substring(0,1))){
            map.add(new String[]{c.substring(0,1),c.substring(1)});
        } else{
            map.get(map.size()-1)[1]=(Integer.parseInt(map.get(map.size()-1)[1])+Integer.parseInt(c.substring(1)))+"";
        }
    }
    StringBuilder sb = new StringBuilder();
    map.forEach(x-> sb.append(x[0]).append(x[1]));
    System.out.println(sb.toString());

编辑:我更改了代码,以便将除 1 以外的其他数字也添加到字符串中,我暂时没有使用流,而是使用循环

我建议的第一件事是将此字符串分解为更易于管理的部分,如下所示:

    String s = "x1x1x1x1a1a1x1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1";
    String[] splitS = s.split("1");
    //Contents of the array are: [x, x, x, x, a, a, x, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a]
    //We can now loop through each string in the string array and count how many we have of what
    ArrayList<String> values = new ArrayList<String>();
    int start = 0, end = 0, grandCounter = 0;
    String current = splitS[0];
    for(int i = 1; i < splitS.length-1; i++){
        if(!splitS[i].equals("x") && current.equals("x")){
            end = i;
            values.add("x" + (end - start));
            grandCounter += (end-start);
            start = end;
            end = 0;
            current = "a";
        } else if(!splitS[i].equals("a") && current.equals("a")){
            end = i;
            values.add("a" + (end - start));
            start = end;
            end = 0;
            current = "x";
            grandCounter += (end-start);
        }
    }
    values.add( "a" + (splitS.length-grandCounter) + "");
    System.out.println(values.toString().replace("[", "").replace(",", "").replace("]", "").replace(" ", ""));

当被告知在控制台中打印时,上面的代码准确地返回了以下内容:x4a2x1a58

如果您对工作有任何疑问或问题,请告诉我!

这里有一个比已经发布的方法更简单的方法:

 public static String customTrim(String s){

String res = "";
String last = "";
int count = 0;

for (int i = 0; i < s.length() - 1; i+=2){

  String curr = "" + s.charAt(i) + s.charAt(i+1);

  if(!curr.equals(last)){
      count = 1;
      res += "" + s.charAt(i) + count;
  }

  else{
    int subLength = ("" + count).length();
    count++;
    res = res.substring(0, res.length()- subLength) + count;
  }

  last = curr;

}
return res;
}

遍历字符并存储最后一个字母字符。对于这些字符中的每一个,解析它后面的数字。如果字母字符与最后一个字符相同,您可以将此数字添加到计数中,否则将旧结果写入输出:

public static String compress(String input) {
    if (input == null || input.isEmpty()) {
        return input;
    }
    char type = ' ';
    int count = 0;
    StringBuilder output = new StringBuilder();
    int index = 0;
    final int length = input.length();
    while (index < length) {
        char elementType = input.charAt(index);

        // parse number
        int elementCount = 0;
        char c;
        for (index++; index < length && Character.isDigit(c = input.charAt(index)); index++) {
            elementCount = 10 * elementCount + (c - '0');
        }

        if (elementType == type) {
            count += elementCount;
        } else {
            // finish counting last type
            output.append(type).append(count);
            type = elementType;
            count = elementCount;
        }
    }
    output.delete(0, 2); // remove substring added for the initial count/type
    output.append(type).append(count); // append last entry
    return output.toString();
}

这允许您输出不同于 1 的数字,例如

compress("a22a20x9")

您可以按照 fabian 发布的方式进行操作,效果很好。但是,我通过三个简单的 if 自己弄明白了。

    StringBuilder sb = new StringBuilder();

    List<String> values = new ArrayList<>();

    String s = "x1x1x1x1a1a1x1x1a1a1a1";
    String[] splitString = s.split("1");
    // "xxxxaaxxaaa"
    // to x4a2x2a3

    String current = splitString[0];
    int occ = 0;

    for(int i = 0; i < splitString.length;i++){

        if(!splitString[i].equals(current)){
            values.add(current+occ);
            occ = 0;
            current = splitString[i];
        }

        if(splitString[i].equals(current)){
            occ++;
        }

        if(i == splitString.length-1){
            values.add(current+occ);
        }

    }

    for (String str: values
         ) {
        sb.append(str);
    }

    System.out.println(sb);
}