자기개발/Java

문자열의 일부를 다른 무자열로 치한 코드

실버블렛 2012. 1. 11. 11:07
반응형

class StringReplace
{
 

  private String source = "";
  private StringBuffer buffer;
  private int length;

  public int length(){
   return length;
  }

  StringReplace(String source){
   this.source = source;
   buffer = new StringBuffer(length + 100);
  }
  public String replace(String old, String nw){
   return replace(old, nw, 0);
  }

  public String replace(String old, String nw, int pos){
   int index = 0;
   if (old == null || nw == null){
    return "null";
   }

   if ( (index = source.indexOf(old, pos)) != -1){
    buffer.append(source.substring(pos, index));
    buffer.append(nw);
    replace(old, nw, index + old.length() );
   } else {
    buffer.append(source.substring(pos) );
   }

   return buffer.toString();
  }

 public static void main(String[] args)
 {
  String str = "000111222333111222333";
  System.out.println(str);
  StringReplace sr = new StringReplace(str);
  System.out.println(sr.replace("111","AAA"));
 } 
}

/*
문자열의 일부를 다른 문자열로 치환하는 클래스를 만들기 위해
1.입력받을 문자열(source)와 치환한 문자열(StringBuffer)을 멤버변수로 선언하는 클래스 StringReplace를 만든다.
2.작업할 문자를 입력받는 생성자 StringReplace(String source)를 작성한다.
3.작업을 시작할 위치와 문자열 A와 B를 입력 받아 A를 B로 치환하는 replace(String old, String nw, int pos)를 만든다.
   1.입력한 값이 유효한지 판단한다.
   2.source에서 해당 문자열을 발견할시 치환한다.
   3.발견한 위치 이후부터 다시 치환을 시작한다.(재귀호출 사용)
   4.더 이상 치환할 문자열을 발견 못하면 나머지 문자열을 작업 결과에 붙인다.
   5.문자열의 처음부터 치환을 하는 replace(String old, String nw)를 작성한다.
   6.StringReplace의 기능을 테스트할 코드를 작성한다.
*/

반응형

'자기개발 > Java' 카테고리의 다른 글

Chapter 5 배열(Array)  (0) 2012.01.21
Chapter 4 조건문과 반복문  (0) 2012.01.12
Chapter 3 연산자  (0) 2012.01.12
Chapter 2. 변수  (0) 2012.01.12
JDK 1.7.0 설치  (0) 2012.01.11