简体   繁体   English

请帮助我了解以下用法:\\ 0

[英]Please help me understand this use of: \0

I'm working on an assignment for class and a friend helped me write some code, and although I've looked up this character \\0 and read the explanations, I'm requesting that someone explain exactly what it is doing in this method. 我正在为班级分配作业,一个朋友帮助我编写了一些代码,尽管我已经查找了\\ 0这个字符并阅读了说明,但我仍要求某人确切地说明此方法的作用。 Thank you so much. 非常感谢。 So again, I'm wondering the exact function or use of this character in my code: \\0. 同样,我想知道我的代码\\ 0中该字符的确切功能或用法。

public String runLengthEncoding(String str){
  String encoded = "";
  char prev = '\0';
  char curr;
  int counter = 1;

  for (int i = 0; i < str.length(); i++) {
     curr = str.charAt(i);
        if(prev == curr) {
           //System.out.println("prev == curr");
           counter = counter + 1;
        }
        else {
           if(i != 0) {
              //System.out.println("encoded += counter + prev");
              encoded += Integer.toString(counter) + prev;
              //System.out.println(encoded);
              counter = 1;
           }
        }
        //System.out.println(Integer.toString(i) + str.length());
        if(i == str.length() - 1) {
            encoded += Integer.toString(counter) + curr;
           //System.out.println(encoded);
           counter = 1;
        }
     prev = curr;
     //System.out.println(i + ", " + prev + ", " + curr);
  }

  return encoded;

The purpose of this method is to iterate over a String, count the number of same characters at sequential indices of the String and generate a representative String of the original String. 此方法的目的是遍历String,在String的顺序索引处计算相同字符的数量,并生成原始String的代表性String。 For example, if the original String is "RRRRSTTT", the method should return the String "4R1S3T". 例如,如果原始字符串为“ RRRRSTTT”,则该方法应返回字符串“ 4R1S3T”。 It is working great, I just had help coding this as I am quite new and am wondering exactly how \\0 works and what it is used for. 效果很好,我刚刚对它进行了编码,因为我还很新,我想知道\\ 0的工作原理以及它的用途。

They are using a NULL character as a starting value for the variable, so when they iterate, prev will never match the first character of the string that was passed (at least, not in the example you provided) 他们使用NULL字符作为变量的起始值,因此在进行迭代时, prev永远不会与传递的字符串的第一个字符匹配(至少在您提供的示例中不这样)

It's simply a placeholder for an uninitialized spot for placing the last character seen. 它只是用于放置最后看到的字符的未初始化位置的占位符。

The function is replacing multiples of letters with a count and then a character. 该功能是先用一个计数和一个字符替换字母的倍数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM