KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > speedo > tools > StringReplace


1 /**
2  * Copyright (C) 2001-2004 France Telecom R&D
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */

18 package org.objectweb.speedo.tools;
19
20
21 /**
22  *
23  * @author S.Chassande-Barrioz
24  */

25 public class StringReplace {
26     public static String JavaDoc replaceChar(char oldChar, char newChar, String JavaDoc s) {
27         char[] cs = s.toCharArray();
28         for (int i = 0; i < cs.length; i++) {
29             if (cs[i] == oldChar) {
30                 cs[i] = newChar;
31             }
32         }
33         return new String JavaDoc(cs);
34     }
35     public static String JavaDoc replaceString(String JavaDoc old, String JavaDoc neo, String JavaDoc str) {
36         if (str == null || str.length() == 0) {
37             return str;
38         }
39         int i = 0;
40         int oldSize = old.length();
41         int neoSize = neo.length();
42         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(str);
43         int begin = 0;
44         int idx = sb.indexOf(old, begin);
45         while(idx != -1) {
46             sb.delete(idx, idx + oldSize);
47             sb.insert(idx, neo);
48             begin = idx + neoSize;
49             if (begin < sb.length()) {
50                 idx = sb.indexOf(old, begin);
51             } else {
52                 idx = -1;
53             }
54         }
55         
56         return sb.toString();
57     }
58
59     public static String JavaDoc toJavaPattern(String JavaDoc str) {
60         str = StringReplace.replaceString("(", "\\(", str);
61         str = StringReplace.replaceString(")", "\\)", str);
62         str = StringReplace.replaceString(".", "\\.", str);
63         str = StringReplace.replaceString("*", ".*", str);
64         str = StringReplace.replaceString("?", ".?", str);
65         return str;
66     }
67 }
68
Popular Tags