View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    * 
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3;
18  
19  /**
20   * <p>Operations on {@code CharSet} instances.</p>
21   *
22   * <p>This class handles {@code null} input gracefully.
23   * An exception will not be thrown for a {@code null} input.
24   * Each method documents its behaviour in more detail.</p>
25   * 
26   * <p>#ThreadSafe#</p>
27   * @see CharSet
28   * @since 1.0
29   * @version $Id: CharSetUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
30   */
31  public class CharSetUtils {
32  
33      /**
34       * <p>CharSetUtils instances should NOT be constructed in standard programming.
35       * Instead, the class should be used as {@code CharSetUtils.evaluateSet(null);}.</p>
36       *
37       * <p>This constructor is public to permit tools that require a JavaBean instance
38       * to operate.</p>
39       */
40      public CharSetUtils() {
41        super();
42      }
43  
44      // Squeeze
45      //-----------------------------------------------------------------------
46      /**
47       * <p>Squeezes any repetitions of a character that is mentioned in the
48       * supplied set.</p>
49       *
50       * <pre>
51       * CharSetUtils.squeeze(null, *)        = null
52       * CharSetUtils.squeeze("", *)          = ""
53       * CharSetUtils.squeeze(*, null)        = *
54       * CharSetUtils.squeeze(*, "")          = *
55       * CharSetUtils.squeeze("hello", "k-p") = "helo"
56       * CharSetUtils.squeeze("hello", "a-e") = "hello"
57       * </pre>
58       *
59       * @see CharSet#getInstance(java.lang.String...) for set-syntax.
60       * @param str  the string to squeeze, may be null
61       * @param set  the character set to use for manipulation, may be null
62       * @return the modified String, {@code null} if null string input
63       */
64      public static String squeeze(final String str, final String... set) {
65          if (StringUtils.isEmpty(str) || deepEmpty(set)) {
66              return str;
67          }
68          final CharSet chars = CharSet.getInstance(set);
69          final StringBuilder buffer = new StringBuilder(str.length());
70          final char[] chrs = str.toCharArray();
71          final int sz = chrs.length;
72          char lastChar = ' ';
73          char ch = ' ';
74          for (int i = 0; i < sz; i++) {
75              ch = chrs[i];
76              // Compare with contains() last for performance.
77              if (ch == lastChar && i != 0 && chars.contains(ch)) {
78                  continue;
79              }
80              buffer.append(ch);
81              lastChar = ch;
82          }
83          return buffer.toString();
84      }
85  
86      // Count
87      //-----------------------------------------------------------------------
88      /**
89       * <p>Takes an argument in set-syntax, see evaluateSet,
90       * and returns the number of characters present in the specified string.</p>
91       *
92       * <pre>
93       * CharSetUtils.count(null, *)        = 0
94       * CharSetUtils.count("", *)          = 0
95       * CharSetUtils.count(*, null)        = 0
96       * CharSetUtils.count(*, "")          = 0
97       * CharSetUtils.count("hello", "k-p") = 3
98       * CharSetUtils.count("hello", "a-e") = 1
99       * </pre>
100      *
101      * @see CharSet#getInstance(java.lang.String...) for set-syntax.
102      * @param str  String to count characters in, may be null
103      * @param set  String[] set of characters to count, may be null
104      * @return the character count, zero if null string input
105      */
106     public static int count(final String str, final String... set) {
107         if (StringUtils.isEmpty(str) || deepEmpty(set)) {
108             return 0;
109         }
110         final CharSet chars = CharSet.getInstance(set);
111         int count = 0;
112         for (final char c : str.toCharArray()) {
113             if (chars.contains(c)) {
114                 count++;
115             }
116         }
117         return count;
118     }
119 
120     // Keep
121     //-----------------------------------------------------------------------
122     /**
123      * <p>Takes an argument in set-syntax, see evaluateSet,
124      * and keeps any of characters present in the specified string.</p>
125      *
126      * <pre>
127      * CharSetUtils.keep(null, *)        = null
128      * CharSetUtils.keep("", *)          = ""
129      * CharSetUtils.keep(*, null)        = ""
130      * CharSetUtils.keep(*, "")          = ""
131      * CharSetUtils.keep("hello", "hl")  = "hll"
132      * CharSetUtils.keep("hello", "le")  = "ell"
133      * </pre>
134      *
135      * @see CharSet#getInstance(java.lang.String...) for set-syntax.
136      * @param str  String to keep characters from, may be null
137      * @param set  String[] set of characters to keep, may be null
138      * @return the modified String, {@code null} if null string input
139      * @since 2.0
140      */
141     public static String keep(final String str, final String... set) {
142         if (str == null) {
143             return null;
144         }
145         if (str.length() == 0 || deepEmpty(set)) {
146             return StringUtils.EMPTY;
147         }
148         return modify(str, set, true);
149     }
150 
151     // Delete
152     //-----------------------------------------------------------------------
153     /**
154      * <p>Takes an argument in set-syntax, see evaluateSet,
155      * and deletes any of characters present in the specified string.</p>
156      *
157      * <pre>
158      * CharSetUtils.delete(null, *)        = null
159      * CharSetUtils.delete("", *)          = ""
160      * CharSetUtils.delete(*, null)        = *
161      * CharSetUtils.delete(*, "")          = *
162      * CharSetUtils.delete("hello", "hl")  = "eo"
163      * CharSetUtils.delete("hello", "le")  = "ho"
164      * </pre>
165      *
166      * @see CharSet#getInstance(java.lang.String...) for set-syntax.
167      * @param str  String to delete characters from, may be null
168      * @param set  String[] set of characters to delete, may be null
169      * @return the modified String, {@code null} if null string input
170      */
171     public static String delete(final String str, final String... set) {
172         if (StringUtils.isEmpty(str) || deepEmpty(set)) {
173             return str;
174         }
175         return modify(str, set, false);
176     }
177 
178     //-----------------------------------------------------------------------
179     /**
180      * Implementation of delete and keep
181      *
182      * @param str String to modify characters within
183      * @param set String[] set of characters to modify
184      * @param expect whether to evaluate on match, or non-match
185      * @return the modified String, not null
186      */
187     private static String modify(final String str, final String[] set, final boolean expect) {
188         final CharSet chars = CharSet.getInstance(set);
189         final StringBuilder buffer = new StringBuilder(str.length());
190         final char[] chrs = str.toCharArray();
191         final int sz = chrs.length;
192         for(int i=0; i<sz; i++) {
193             if(chars.contains(chrs[i]) == expect) {
194                 buffer.append(chrs[i]);
195             }
196         }
197         return buffer.toString();
198     }
199 
200     /** 
201      * Determines whether or not all the Strings in an array are 
202      * empty or not.
203      *
204      * @param strings String[] whose elements are being checked for emptiness
205      * @return whether or not the String is empty
206      */
207     private static boolean deepEmpty(final String[] strings) {
208         if (strings != null) {
209             for (final String s : strings) {
210                 if (StringUtils.isNotEmpty(s)) {
211                     return false;
212                 }
213             }
214         }
215         return true;
216     }
217 }