not set

String Class 의 replace 매서드를 구현하라 본문

java/custom function

String Class 의 replace 매서드를 구현하라

다크곰 2013. 8. 7. 00:56

replace 를 사용하지 않고 replace 매서드를 구현하라.


최대한 해보았는데 버그가 있을 수도 있다.


package my.run;


import my.util.myUtil;


public class Run {

public static void main(String args[]){

myUtil me = new myUtil();

String tmp = "STATIC VOID MAIN";

String result = "";

// my useful function

result = me.myReplace(tmp, "S", "SUPER");

System.out.println(tmp + " => " + result);

}

}


실행용 클래스


package my.util;


/**

 * <PRE>

 *  myUtil Class

 * </PRE>

 * @author mji

 */

public class myUtil {

/*

* replace 와 같은 역할을 하는 함수

* return string

* @author mji

*/

@SuppressWarnings("null")

public String myReplace(String arg, String from, String to){

String tmp = "";

String result = "";


if(arg == null || arg.length() == 0 || 

      from == null || from.length() == 0 || 

      to == null || to.length() == 0){

tmp = "올바른 파라미터 값이 존재 하지 않습니다.";

System.out.println("ERROR => " + tmp);

result = tmp;

} else {

tmp = arg;

// 문자의 위치를 가져옴

int idx = tmp.indexOf(from);

System.out.println("idx => " + idx);

// 해당 문자열이 없을때까지 loop

if(idx == -1){

tmp = "존재하지 않는 문자열입니다.";

result = tmp;

return result;

} else {

while(idx != -1){

result += tmp.substring(0,idx) + to;

tmp = tmp.substring(idx + from.length());

System.out.println("tmp =>" + tmp);

idx = tmp.indexOf(from);

}

result += tmp;

System.out.println("change arg => " + result);

}

}

return result;

}

}

myUtil Class 의 myReplace 매서드