从字符串中删除重复或重复的字符

时间:2016-08-20 22:22:18

标签: java duplicates

如何删除重复字符? 像

  伞应该是Umbrela

     

可能应该是可行的

public static String rem(String s,char c ){
    String result="";

    for (int i = 0; i+1 <s.length(); i++) {
        char a=s.charAt(i);
        char b=s.charAt(i+1);

        if(a!=c || b!=c){
            char d=a;
        IO.put(d+"\n");
    }

}
    return result;
}

1 个答案:

答案 0 :(得分:0)

提示:想想如何使用笔和纸手动完成它?

  1. 从左侧逐个浏览每个角色
  2. 如果当前字符与前一个字符不同,请将字符复制到新字符串
  3. 否则,跳过该角色并转到下一个角色。
  4. 然后,将上面的内容翻译成代码,就像这样(假设一个非空和非空的输入字符串):

        String input = "three";
        StringBuilder output = new StringBuilder();
        char lastChar = input.charAt(0); // get the first character
        output.append(lastChar); // store the first character in the output string
    
        // loop through the rest of the characters, starting from the second char
        for (int i = 1; i < input.length(); i++) {
            char c = input.charAt(i);
            // add the current char to the output, if it is not same as the last char
            // in the output
            if (c != lastChar) {
                output.append(c);
                lastChar = c;
            }
        }
        System.out.println(output);
    

    一旦你学会了正则表达式,就可以更容易地使用正则表达式(参见Andy Turner的评论)

相关问题