2016-11-30 76 views
-1

请求帮助 我需要在'String dst;'中重新引用与控制台
例如相同的结果。输入txt = "aabbc";这给
return dst = "a2b2c1"将sysout更改为字符串

public String compres(String txt) { 

     String dst = ""; 
     char character; 
     int count; 

     for (int i = 0; i < txt.length(); i++) { 
      character = txt.charAt(i); 
      count = 1; 
      while (i < txt.length() - 1 && txt.charAt(i + 1) == character) { 
       count++; 
       i++; 
      } 
      System.out.print(character); 
      System.out.print(count); 
     } 
     return dst; 
} 
+0

你的代码的实际问题是什么? – tnw

+0

这个问题太不清楚了,无法回复 – Coder

+0

考虑使用Character to Integer的[Map](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html)。遇到新字符时,将其添加到地图中,整数值为1.当您看到现有字符时,递增与其相关的整数。然后迭代映射中的每个条目,并将字符/计数配对添加到字符串。 – Ironcache

回答

1

使用StringBuilder。今天

public String compres(String txt) { 

     StringBuilder dst = new StringBuilder(); 
     char character; 
     int count; 

     for (int i = 0; i < txt.length(); i++) { 
      character = txt.charAt(i); 
      count = 1; 
      while (i < txt.length() - 1 && txt.charAt(i + 1) == character) { 
       count++; 
       i++; 
      } 
      System.out.print(character); 
      System.out.print(count); 
      dst.append(character).append(count); 
     } 

     return dst.toString(); 
} 
0

我的队友给了我最简单的sollution我只需要添加在我的循环:

DST + =字符+ “” +计数;

而不是双系统