通过增加连续字符的数量来缩短字符串的表示形式

问题描述 投票:-1回答:1

给出一个不包含(0-9)的随机字符串,我需要通过增加连续字符的数量来缩短该字符串的表示。例如:ggee将导致显示g2e2。我设法实现了该程序并通过各种输入对其进行了测试(正确运行)。我遇到了一个问题,在上述输入下,我似乎无法理解如何显示字符“ e”。我已经跟踪了我的代码多次,但是当“ i”为2/3时,我看不到何时/如何显示“ e”。

String input = new String("ggee");
char position = input.charAt(0);
int accumulator = 1;
for (int i = 1; i < input.length(); i++)
{
    // Correction. Was boolean lastIndexString = input.charAt(i) == (input.charAt(input.length() - 1));
    boolean lastIndexString = i == (input.length() - 1); 
    if (position == input.charAt(i))
    {
        accumulator++;
        if (lastIndexOfString)
            System.out.print(accumulator); // In my mind, I should be printing 
                                           // (input.charAt(i) + "" + accumulator); here
    }
    else //(position != input.charAt(i))
    {
        if (accumulator > 1)
        {
            System.out.print(position + "" + accumulator);
        }
        else
        {
            System.out.print(position + "");
        }
        position = input.charAt(i);
        accumulator = 1;

        if (lastIndexOfString)
           System.out.print(input.charAt(i)); // This is always printing when 
                                              //  I am at the last index of my string, 
                                              //  even ignoring my condition of 
                                              //  (position == input.charAt(i))
    }
}

java string
1个回答
0
投票

基本上,您希望每个字符都没有重复。

        s="ggggggeee"
        StringBuilder s1=new 
         StringBuilder(s) 
           ;
         s1="" ;



       For(int i=0;i<length;i++)
      {
     Int count=0;
        for(int j=i+1;j<length;j++)
        {
       if(s.charAt(i)==s.charAt(j))
       count++;
       else 
         Break;
        } 
     s1=s1.append(s.charAt(i)+""+count);

    } 

     } 

0
投票

在Java 9+中,使用正则表达式查找连续的字符,将执行以下操作:

static String shorten(String input) {
    return Pattern.compile("(.)\\1+").matcher(input)
            .replaceAll(r -> r.group(1) + r.group().length());
}

Test

System.out.println(shorten("ggggeecaaaaaaaaaaaa"));
System.out.println(shorten("ggggee😀😀😀😁😁😁😁"));

输出

g4e2ca12
g4e2😀6😁8

但是,如您所见,如果输入字符串包含补充平面中的Unicode字符(例如Emoji字符),则该代码不起作用。

小的修改将解决此问题:

static String shorten(String input) {
    return Pattern.compile("(.)\\1+").matcher(input)
            .replaceAll(r -> r.group(1) + r.group().codePointCount(0, r.group().length()));
}

输出

g4e2ca12
g4e2😀3😁4
© www.soinside.com 2019 - 2024. All rights reserved.