2016-08-20 201 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''怎麼辦? –