2013-10-18 3 views
0

이 간단한 암호화 프로그램을 만들려고 노력했지만 몇 가지 사항을 파악할 수 없습니다. 내가 입력해야 문구는 문자열을정규 표현식을 사용하여 부분 문자열 바꾸기

This is a ag',rery dug>?/ijeb..w ssadorninjeb..w 

를 반환하지만 내가 대신 내가 돌아를 입력하면

This is a very big morning. 

이다 나는 왜, 어떻게 해결하는 방법을 이해하지 않습니다

This is a ajedg>P/..w',rery dg>P/ijedg>P/..w ssadorninjedg>P/..w 

그것? 나는 지금도 약 1 개월 동안 자바를 배웠다. 그래도 나는 여전히 신선하다. 비슷한 질문이 있으면 이미 거기에 링크 해주세요. 그러면이 글을 삭제할 것입니다. 당신은 '당신은 모든 b의 가져 오기'상기 g 교체에서의도 b 교체 교체 할 때 당신은 g의 교체를 대체

import static java.lang.System.out; 
import java.util.Scanner; 
class Encryption { 
    public static void main(String[] args) { 
     Scanner userInput = new Scanner(System.in); 
     Crypto user1 = new Crypto(); 
     out.print("Please enter in a sentence: "); 
     String user = userInput.nextLine(); 
     user1.encrypt(user); 
     out.print(user1.getEncrypt()); 
    } 
} 

public Crypto() { } 
public String myEn; 
public void encrypt(String Sentence) { 
    myEn = Sentence.replaceAll("v","ag',r") 
        .replaceAll("m" , "ssad") 
        .replaceAll("g" , "jeb..w") 
        .replaceAll("b" , "dg>P/"); 
} 

public String getEncrypt() { 
     return myEn; 
} 
} 

답변

0

그래서 다음 b을 포함

여기에 코드입니다. 또한 대한 v의 당신이 할 수있는 것은

Sentence.replaceAll("g" , "jeb..w") 
    .replaceFirst("b" , "dg>P/")  // as no g's before b's and only want to replace the first 
    .replaceFirst("v","ag',r") 
    .replaceFirst("m" , "ssad"); 

입니다

그러나이 한 문장이에서만 작동합니다. 당신이 무엇을 할 수 있는지


:

  1. 모든 캐릭터의지도를 만들기는 교체가 교체된다.
  2. 원래 문자열에서 바꿀 각 문자의 색인 목록을 만듭니다.
  3. 는 목록의 순서 (최고 최저로) 목록의 첫 번째 인덱스에서 시작
  4. (마지막 문자 대체 될)지도
  5. 반복 4에서의 교체와 그 인덱스에있는 문자를 대체 역
  6. 문자열을 거꾸로 작업합니다.
2

다른 출력을 얻는 이유는 체인 대체가 이전 대체 값의 반환 값을 사용하기 때문입니다. 따라서 귀하의 경우 v이있는 경우 g이 포함 된 ag',r으로 변경됩니다. 그러면 greplaceAll("g" , "jeb..w")을 트리거합니다.

당신은을 대체의 순서를 변경해야합니다, 이런 일이 발생하지 않도록하려면 그러나

Sentence.replaceAll("g" , "jeb..w") 
     .replaceAll("b" , "dg>P/") 
     .replaceAll("v","ag',r") 
     .replaceAll("m" , "ssad"); 

를, 처음 두 하나는 g에가있는 문자열로 b을 바꾸기 때문에 문을 수정할 수 없습니다 교체 그 반대의 경우도 있으므로 대체하려는 문자를 변경하고 싶을 수 있습니다.

0

먼저 replace()이 아닌 replaceAll()을 사용해야합니다. 둘 모두 발견 된 모든 일치를 대체하지만 replaceAll()은 정규 표현식을 사용하여 match 및 replace()에 정규 표현식을 사용합니다.

다음으로 대체품이 서로의 방식으로 연결되므로 StringBuffer를 사용하고 8 번째에서 작업하고 한 번에 한 문자 씩 뒤쪽으로 끝냅니다.

복호화는 왼쪽부터 한 번에 한 문자 씩 작동해야합니다.

0

다른 사람들이 이미 문제를 말했듯이 몇 번의 반복 (replaceAll 호출)으로 문자를 대체하는 경우가 있습니다. 다른 문자를 대체하는 데 사용되는 문자를 바꾸지 않으려면 appendReplacementappendTailMatcher 클래스에서 사용할 수 있습니다.

This is a ag',rery dg>P/ijeb..w ssadorninjeb..w. 

봐라 : 여기

// We need to store somewhere info about original and its replacement 
// so we will use Map 
Map<String, String> replacements = new HashMap<>(); 
replacements.put("v", "ag',r"); 
replacements.put("m", "ssad"); 
replacements.put("g", "jeb..w"); 
replacements.put("b", "dg>P/"); 

// we need to create pattern which will find characters we want to replace 
Pattern pattern = Pattern.compile("[vmgb]");//this will do 

Matcher matcher = pattern.matcher("This is a very big morning."); 

StringBuffer sb = new StringBuffer();// this will be used to create 
            // string with replaced characters 

// lets start replacing process 
while (matcher.find()) {//first we need to find our characters 

    // then pick from map its replacement 
    String replacement = replacements.get(matcher.group()); 
    // and pass it to appendReplacement method 
    matcher.appendReplacement(sb, replacement); 

    // we repeat this process until original string has no more 
    // characters to replace 
} 
//after all we need to append to StringBuffer part after last replacement 
matcher.appendTail(sb); 

System.out.println(sb); 

출력처럼 할 수있는 방법이다.

관련 문제