2016-08-20 210 views
-2

如何删除重复字符? 像删除字符串中的重复或重复字符

伞应该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

什么语言?你有什么尝试?那么不同的情况呢?角色必须彼此接踵而至(“伊甸园”会变成“艾德”)吗? – Marvin

+0

在Java中。 public static String rem(String s,char c){0} {0}对于(int i = 0; i + 1 Khalid

+2

请将该代码编辑到您的问题中,并说明您卡在哪里。 – Marvin

回答

0

提示:想想你将如何做手工,使用笔和纸?

  1. 经历从左边
  2. 每个字符逐个如果当前字符不一样的前一个字符,字符复制到新的字符串
  3. 否则,跳过字符,并移动到下一个。

然后,转换到上述代码,会是这样的(假设非空和非空输入字符串):使用一次正则表达式

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); 

这可以进一步容易地进行你已经学会了他们(见安迪特纳的评论)

+0

如果字符串的第一个字符是“0”,该怎么办? –

+0

@AndyTurner我正在懒惰:(,回答编辑使用空字符文字 – rohitvats

+0

同样的问题:如果字符串的第一个字符是''\ 0''怎么办? –