我的for循环为我的字符串压缩有点偏.过去5天我一直在做这项任务,我无法弄清楚我的生活有什么不对.有人可以帮我吗?
例如,我传递了字符串“TTTTrrrEe”,而不是获得T4r3Ee,我得到了T4r3EeTT.我不知道为什么它会像那样跳回到字符串的开头,但我越来越近了.我们只能使用字符串类中的charAt,equals,length和substring.
有人可以通过帮助纠正我的逻辑来帮助指导我朝着正确的方向前进吗?我仍然想尝试自己编写代码,看看它是如何分配的.
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; }
解决方法
由于这是一个学习练习,我不会尝试修复您的代码,只需指出一些工作要做到正确:
>如果将for循环条件更改为i
>当count为零(你的计数< 1条件相当于count == 0)时,除了temp的第一个字符后跟count之外,你还要打印当前字符和后面的字符.这看起来不正确.
>不是在循环中增加临界值,而是在每次迭代时设置它.这看起来不正确.
>在循环中增加temp的更好方法是使用StringBuilder
和append(),而不是使用普通的String,并执行连接.