Run-length decompression

最后都变了- 提交于 2019-12-02 17:02:11

问题


CS student here. I want to write a program that will decompress a string that has been encoded according to a modified form of run-length encoding (which I've already written code for). For instance, if a string contains 'bba10' it would decompress to 'bbaaaaaaaaaa'. How do I get the program to recognize that part of the string ('10') is an integer?

Thanks for reading!


回答1:


A simple regex will do.

final Matcher m = Pattern.compile("(\\D)(\\d+)").matcher(input);
final StringBuffer b = new StringBuffer();
while (m.find()) 
  m.appendReplacement(b, replicate(m.group(1), Integer.parseInt(m.group(2))));
m.appendTail(b);

where replicate is

String replicate(String s, int count) {
  final StringBuilder b = new StringBuilder(count);
  for (int i = 0; i < count; i++) b.append(s);
  return b.toString();
}



回答2:


Not sure whether this is one efficient way, but just for reference

for (int i=0;i<your_string.length();i++)
    if (your_string.charAt(i)<='9' && your_string.charAt(i)>='0')
        integer_begin_location = i;



回答3:


I think you can divide chars in numeric and not numeric symbols.

When you find a numeric one (>0 and <9) you look to the next and choose to enlarge you number (current *10 + new) or to expand your string




回答4:


Assuming that the uncompressed data does never contain digits: Iterate over the string, character by character until you get a digit. Then continue until you have a non-digit (or end of string). The digits inbetween can be parsed to an integer as others already stated:

int count = Integer.parseInt(str.substring(start, end));



回答5:


Presuming that you're not asking about the parsing, you can convert a string like "10" into an integer like this:

int i = Integer.parseInt("10");


来源:https://stackoverflow.com/questions/20131787/run-length-decompression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!