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. Thank you so much. So again, I'm wondering the exact function or use of this character in my code: \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. For example, if the original String is "RRRRSTTT", the method should return the String "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.