2016-08-20 9 views
-2

どのように私は、繰り返し文字を削除することができますか?文字列から繰り返しまたはdulplicate文字を削除

傘のよう は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){ 文字列の結果= ""; がため(INT i = 0; I + 1 Khalid

+2

あなたの質問にはそのコードを編集してください。 – Marvin

答えて

0

ヒント:あなたはペンと紙を使用して、手動でそれを行うだろうかを考えてみて?左

  • から一つの各文字1による

    1. Goが現在の文字は、
    2. そうでない場合は、新しい文字列に文字をコピーした文字をスキップしてに移動し、前の文字と同じでない場合次の。

    そして、コードに上記の変換、(非ヌルおよび非空の入力文字列を仮定して)、このようなものであろう:

    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

    acomodationすべきですか? –

    +0

    @AndyTurner私は怠け者でした:(返事はnullのcharリテラルを使用するように編集されました – rohitvats

    +0

    同じ問題:文字列の最初の文字が ''\ 0''の場合はどうですか? –

    関連する問題