Java – string packed loop logic

My for loop is a bit biased for my string compression I've been doing this task for the past five days. I can't figure out what's wrong with my life Can someone help me?

For example, I passed the string "ttttrree" instead of getting t4r3ee, and I got t4r3eett I don't know why it jumps back to the beginning of the string like that, but I'm getting closer and closer We can only use charat, equals, length and substring in the string class

Can someone help guide me in the right direction by helping to correct my logic? I still want to try to write my own code and see how it is allocated

public static String compress(String s){
    int count = 0;
    String temp = s.substring(0,1);
    for(int i = 0; i < s.length(); i++){
        if(i !=s.length()-1){
            if(temp.equals(s.substring(i,i+1))){
                count++;

            }else{

                if(count < 1){
                    System.out.print(s.substring(i,i+2));
                    System.out.print(temp.substring(0,1) );
                }else{
                    System.out.print("" + temp.substring(0,1) + count);
                    i--;
                    temp = s.substring(count,count+1);
                    System.out.println(" temp is Now " + temp);

                    count = 0;
                    //i--;
                }
            }
        }

    }

    System.out.println(temp);

    return temp;
}

Solution

Since this is a learning exercise, I won't try to fix your code, just point out some things to do correctly:

>If you change the for loop condition to I > it is easier (and faster) to compare individual characters than substrings Get the character at position I by calling char ch1 = s.charat (I) and compare the two characters with the = = operator instead of calling equals(). > When count is zero (your count < 1 equals count = = 0), you have to print the current character and subsequent characters in addition to the first character of temp followed by count This doesn't look right. > Instead of increasing the threshold in the loop, set it at each iteration This doesn't look right. > A better way to add temp to the loop is to use StringBuilder and append () instead of using a normal string and perform a connection

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>