| StringUtilities.java |
1 package comtest;
2 import java.util.Scanner;
3 import java.io.File;
4 import java.io.FileNotFoundException;
5
6 /**
7 * A collection of static string handling functions
8 * to make the string handling in ComTest more easy.
9 *
10 * @author vesal
11 * @version 22.9.2007
12 */
13 public class StringUtilities { // NOPMD by vesal on 13.1.2008 15:27
14
15 /**
16 * Chars that are handled as quote chars
17 */
18 public static final String QUOTES = "\"'";
19 /*
20 #STATICIMPORT
21 #PACKAGEIMPORT
22 */
23
24 /**
25 * Splits s to pieces from where. Quotes is taken account
26 * so where inside quotes, then it is ignored.
27 * @param s string to split
28 * @param where from where to split
29 * @param jump how much delete from each part
30 * @param trim to trim or not the parts
31 * @return list of parts
32 * @example
33 * <pre name="testSplitBy">
34 * String s = "first; second;\"third;3\";4;";
35 * Strings p = splitBy(s,";",1);
36 * p.size() === 5
37 * p.get(0) === "first"; p.get(1) === " second"; p.get(2) === "\"third;3\""
38 * p.get(3) === "4"; p.get(4) === ""
39 *
40 * s = "first; second;\"third;3\";4";
41 * p = splitBy(s,";",0,true);
42 * p.size() === 4
43 * p.get(0) === "first;"
44 * p.get(1) === "second;"
45 * p.get(2) === "\"third;3\";"
46 * p.get(3) === "4"
47 * </pre>
48 *
49 */
50 public static Strings splitBy(String s, String where, int jump, boolean trim) {
51 Strings parts = new Strings();
52 int p = 0, p2;
53 while ( true ) {
54 p2 = indexOfNotInQuotes(s, where, QUOTES,p);
55 if ( p2 < 0 ) break;
56 String part = s.substring(p,p2+where.length()-jump);
57 if ( trim ) part = part.trim();
58 p = p2+where.length();
59 parts.add(part);
60 }
61 parts.add(s.substring(p));
62 return parts;
63 }
64
65 /**
66 * Splits s to pieces from where. Quotes is taken account
67 * so where inside quotes, then it is ignored.
68 * @param s string to split
69 * @param where from where to split
70 * @param jump how much delete from each part
71 * @return list of parts
72 */
73 public static Strings splitBy(String s, String where, int jump) {
74 return splitBy(s, where, jump, false);
75 }
76
77
78 /**
79 * Splits s to pieces from where. Quotes is taken account
80 * so where inside quotes, then it is ignored.
81 * @param s string to split
82 * @param where from where to split
83 * @return list of parts
84 *
85 * @example
86 * <pre name="test">
87 * Strings p;
88 * p = splitBy("one|two|three","|");
89 * p.size() === 3;
90 * p.get(0) === "one";
91 * p.get(1) === "two";
92 * p.get(2) === "three";
93 *
94 * p = splitBy("one|","|");
95 * p.size() === 2;
96 * p.get(0) === "one";
97 * p.get(1) === "";
98 *
99 * p = splitBy("one","|");
100 * p.size() === 1;
101 * p.get(0) === "one";
102 *
103 * p = splitBy("","|");
104 * p.size() === 1;
105 * p.get(0) === "";
106 *
107 * </pre>
108 */
109 public static Strings splitBy(String s, String where) {
110 return splitBy(s, where, where.length() , false);
111 }
112
113
114
115 /**
116 * Find first instance of what that is not inside of quotes
117 * @param s from where to find
118 * @param what string to find
119 * @param quote what chars are used as a quote
120 * @param pos position where to start
121 * @return index of first occurrence or -1 if not found
122 */
123 public static int indexOfNotInQuotes(String s, String what, String quote, int pos) { // NOPMD by vesal on 13.1.2008 15:27
124 if ( quote.equals("") ) return s.indexOf(what); // NOPMD by vesal on 13.1.2008 15:27
125 if ( quote.indexOf(what) >= 0 ) return s.indexOf(what);
126
127 boolean inQuote = false;
128 char quoteChar = 0;
129
130 for (int i=pos; i<s.length(); i++) {
131 if ( inQuote && s.charAt(i) == '\\' ) { i += 1; continue; }
132 int p = quote.indexOf(s.charAt(i));
133 if ( !inQuote && p >= 0 ) {
134 inQuote = true;
135 quoteChar = quote.charAt(p);
136 continue;
137 }
138 if ( inQuote ) {
139 if ( s.charAt(i) == quoteChar ) inQuote = false;
140 continue;
141 }
142 if ( s.startsWith(what,i) ) return i;
143 }
144 return -1;
145 }
146
147 /**
148 * Find first instance of what that is not inside of quotes
149 * @param s from where to find
150 * @param what string to find
151 * @return index of first occurrence or -1 if not found
152 */
153 public static int indexOfNotInQuotes(String s, String what) {
154 return indexOfNotInQuotes(s,what,QUOTES);
155 }
156
157
158 /**
159 * Find first instance of what that is not inside of quotes
160 * @param s from where to find
161 * @param what string to find
162 * @param quote what chars are used as a quote
163 * @return index of first occurrence or -1 if not found
164 * @example
165 * <pre name="testIndexOfNotInQuotes">
166 * indexOfNotInQuotes("a = a+1; // add one ", "//","\"") === 9
167 * indexOfNotInQuotes("a = a+1; ", "//","\"") === -1
168 * indexOfNotInQuotes("s = \"//\"; // s is comment", "//","\"") === 10
169 * indexOfNotInQuotes("s = \"//\"; ", "//","\"") === -1
170 * indexOfNotInQuotes("s = \"a\"; // \"//\" ", "//","\"") === 10
171 * indexOfNotInQuotes("s = \"a\"; // \"//\" ", "\"","\"") === 4
172 * indexOfNotInQuotes("s = \"a\"; // \"//\" ", "a","") === 5
173 * indexOfNotInQuotes("s = \"a\"; c='a'; d=a; ", "a","\"'") === 18
174 * </pre>
175 */
176 public static int indexOfNotInQuotes(String s, String what, String quote) {
177 return indexOfNotInQuotes(s, what, quote,0);
178 }
179
180 /**
181 * Removes n instances of what from the beginning of s
182 * @param s where to remove
183 * @param what string what to remove
184 * @param n how many times to remove
185 * @return string without what in the beginning
186 * @example
187 * <pre name="testRemoveFromBeginingN">
188 * removeFromBegining("* a=a+1;","*",2) === " a=a+1;"
189 * removeFromBegining("*** a=a+1;","*",2) === "* a=a+1;"
190 * removeFromBegining("* ** a=a+1;","*",2) === " ** a=a+1;"
191 * </pre>
192 */
193 public static String removeFromBegining(String s, String what, int n) {
194 String result = s;
195 int i = 0;
196 while ( i < n && result.startsWith(what)) {
197 i++;
198 result = result.substring(what.length());
199 }
200 return result;
201 }
202
203 /**
204 * Removes all instances of what from the beginning of s
205 * @param s where to remove
206 * @param what string what to remove
207 * @return string without what in the beginning
208 * @example
209 * <pre name="testRemoveFromBegining">
210 * removeFromBegining("* a=a+1;","*") === " a=a+1;"
211 * removeFromBegining("*** a=a+1;","*") === " a=a+1;"
212 * removeFromBegining("* ** a=a+1;","*") === " ** a=a+1;"
213 * </pre>
214 */
215 public static String removeFromBegining(String s, String what) {
216 String result = s;
217 while ( result.startsWith(what))
218 result = result.substring(what.length());
219 return result;
220 }
221
222 /**
223 * Removes all instances of what from the beginning of s
224 * If there is only spaces before s, then remove them also.
225 * @param s where to remove
226 * @param what string what to remove
227 * @return string without what in the beginning
228 * @example
229 * <pre name="testRemoveFromBeginingTrim">
230 * removeFromBeginingTrim(" * a=a+1;","*") === " a=a+1;"
231 * removeFromBeginingTrim(" *** a=a+1;","*") === " a=a+1;"
232 * removeFromBeginingTrim(" * ** a=a+1;","*") === " ** a=a+1;"
233 * removeFromBeginingTrim(" a=a+1;","*") === " a=a+1;"
234 * </pre>
235 */
236 public static String removeFromBeginingTrim(String s, String what) {
237 int p = indexOfNotInQuotes(s, what);
238 if ( p < 0 ) return s;
239 for ( int i=0; i<p; i++ ) {
240 if ( !Character.isWhitespace(s.charAt(i)) ) return s;
241 }
242 String result = s.trim();
243 while ( result.startsWith(what) )
244 result = result.substring(what.length());
245 return result;
246 }
247
248 /**
249 * Returns a string where all after afterWhat string is removed
250 * Also the afterWhat is removed. If afterWhat is inside
251 * quotes, then it is not affected.
252 * @param s string to handle
253 * @param afterWhat string to look for
254 * @return the handled string
255 * @example
256 * <pre name="testRemoveAllAfter">
257 * removeAllAfter("a = a+1; // add one ", "//") === "a = a+1; "
258 * removeAllAfter("a = a+1; ","//") === "a = a+1; "
259 * removeAllAfter("s = \"//\"; // s is comment", "//" ) === "s = \"//\"; "
260 * removeAllAfter("s = \"//\"; " ,"//") === "s = \"//\"; "
261 * removeAllAfter("s = \"a\"; // \"//\" " ,"//") === "s = \"a\"; "
262 * </pre>
263 */
264 public static String removeAllAfter(String s, String afterWhat) {
265 int i = indexOfNotInQuotes(s,afterWhat,QUOTES);
266 if ( i < 0 ) return s;
267 return s.substring(0,i);
268 }
269
270 /**
271 * Adds a new part to filename
272 * @param fileName filename to change
273 * @param newPart part to add
274 * @return filename + newPart
275 * @example
276 * <pre name="testAddToName">
277 * addToName("my.java","Test") === "myTest.java"
278 * addToName("my","Test") === "myTest"
279 * </pre>
280 */
281 public static String addToName(String fileName, String newPart) {
282 int i = fileName.lastIndexOf('.');
283 if ( i < 0 ) return fileName + newPart;
284 return fileName.substring(0,i) + newPart + fileName.substring(i);
285 }
286
287
288 /**
289 * Returns just the file part from fileName. No path, no extension
290 * @param fileName
291 * @return only file name part from fileName
292 * @example testJustFilePart
293 * <pre name="testJustFilePart">
294 * justFilePart("myTest.java") === "myTest"
295 * justFilePart("myTest") === "myTest"
296 * justFilePart("/users/my/java/myTest.java") === "myTest"
297 * justFilePart("/users/my.prg/java/myTest.java") === "myTest"
298 * justFilePart("/users/my.prg/java/myTest") === "myTest"
299 * justFilePart("/users/my.prg/java/myTest/") === ""
300 * justFilePart("e:\\users\\my.prg\\java\\myTest") === "myTest"
301 * justFilePart("\\users\\my.prg\\java\\myTest") === "myTest"
302 * justFilePart("e:myTest.java") === "myTest"
303 * </pre>
304 */
305 public static String justFilePart(String fileName) {
306 int id = fileName.lastIndexOf('.');
307 int is = fileName.lastIndexOf('/');
308 int ib = fileName.lastIndexOf('\\');
309 int idd = fileName.lastIndexOf(':');
310 if ( idd > is ) is = idd;
311 if ( ib > is ) is = ib;
312 if ( id < is ) id = fileName.length();
313 if ( id < 0 ) id = fileName.length();
314 return fileName.substring(is+1,id);
315 }
316
317
318 /**
319 * Removes from s the first instance of what
320 * @param s where to remove
321 * @param what what string to remove
322 * @return s without first instance on what
323 * @example
324 * <pre name="test">
325 * remove($s,$what) === $result;
326 *
327 * $s | $what | $result
328 * ----------------------------------
329 * "aab" | "a" | "ab"
330 * "bab" | "a" | "bb"
331 * "bba" | "a" | "bb"
332 * </pre>
333 *
334 * @example
335 * <pre name="test">
336 * remove($s,$what) === $result;
337 *
338 * $s | $what | $result
339 * ----------------------------------
340 * "\"aa\"b" | "a" | "\"aa\"b"
341 * "\"a\"ab" | "a" | "\"a\"b"
342 * </pre>
343 */
344 public static String remove(String s, String what) {
345 int p = indexOfNotInQuotes(s, what);
346 if ( p < 0 ) return s;
347 return s.substring(0,p)+s.substring(p+what.length());
348 }
349
350
351 /**
352 * Read the file and return the contents as a ArrayList
353 * @param fileName the file name to read
354 * @return null if problems, otherwise the file contents
355 *
356 * @example
357 * <pre name="testGetFileContents">
358 * Strings list = getFileContents("comtest/StringUtilities.java");
359 * int lastn = list.size()-1;
360 * lastn > 200 === true;
361 * list.get(0) === "package comtest;";
362 * list.get(lastn) === "}";
363 * list = getFileContents("comtest/StringUtilitiesXYZ.java");
364 * list === null;
365 *
366 * </pre>
367 */
368 public static Strings getFileContents(String fileName) {
369 Scanner scanner = null;
370
371 try {
372 scanner = new Scanner(new File(fileName));
373
374 Strings lines = new Strings();
375
376 while ( (scanner.hasNextLine()) ) {
377 lines.add(scanner.nextLine());
378 }
379 return lines;
380 } catch (FileNotFoundException e) {
381 return null;
382 }
383 finally {
384 if ( scanner != null ) scanner.close();
385 }
386 }
387
388 /**
389 * Counts the index in ending word when
390 * the builded string should contain
391 * end-string as last characters.
392 * @param start The starting string.
393 * @param end The required ending.
394 * @return The starting index where end-string should be inserted after the start.
395 * @example
396 * <pre name="test">
397 * countEndIndex("#STATIC","#STATICIMPORT") === 7;
398 * countEndIndex("ABCD","1234") === 0;
399 * countEndIndex("ABCD","ABCD") === 4;
400 * countEndIndex("1234567890#STATIC","#STATICIMPORT") === 7;
401 *
402 * </pre>
403 */
404
405 public static int countEndIndex(String start, String end) {
406 int startLastIdx =start.length();
407 int endLastIdx = end.length();
408 int minLastIdx = Math.min(startLastIdx,endLastIdx);
409 boolean matched = false;
410 for(int i = 1; i<=minLastIdx;i++){
411 boolean regmatch = end.regionMatches(0, start, startLastIdx-i, i);
412 if (regmatch) matched = true;
413 if (! regmatch && matched){
414 return i-1;
415 }
416 }
417 if (matched){
418 return minLastIdx;
419 } else {
420 return 0;
421 }
422 }
423
424 /*
425 public static int countEndIndex(String start, String end) {
426 if ( !end.startsWith(start) ) return 0;
427 return start.length();
428 }
429 */
430
431
432 /**
433 * Searches what backwards from pos and returns position found
434 * @param s where to search
435 * @param what to search
436 * @param pos where to start search
437 * @return position found or -1 if not found
438 *
439 * @example
440 * <pre name="test">
441 * indexOfBack("0123456789","4",8) === 4;
442 * indexOfBack("0123456789","9",8) === -1;
443 * indexOfBack("0123456789","4",4) === 4;
444 * indexOfBack("0123456789","4",3) === -1;
445 * indexOfBack(null,"4",5) === -1;
446 * indexOfBack(null,null,5) === -1;
447 * indexOfBack("012345678",null,5) === -1;
448 * indexOfBack("0123456789","4",18) === 4;
449 * indexOfBack("0123456789","",18) === 10;
450 * indexOfBack("0123456789","",5) === 5;
451 * indexOfBack("0123456789","abc",15) === -1;
452 * </pre>
453 */
454 public static int indexOfBack(String s, String what, int pos) {
455 if ( s == null ) return -1;
456 if ( what == null ) return -1;
457 if ( pos < 0 ) return -1;
458 int p = pos;
459 int len = what.length();
460 if ( p >= s.length() ) p = s.length() - len;
461 if ( p < 0 ) return -1;
462
463 while ( p >= 0 && !s.substring(p,p+len).equals(what) ) p--;
464
465 return p;
466 }
467
468
469 /**
470 * Returns indent string copied from line. Search for
471 * line is started backwards from pos.
472 * @param line line to look indent template
473 * @param pos where to start looking
474 * @return the same indent that current line has
475 *
476 * @example
477 * <pre name="test">
478 * getLineIndent("first\n second\n",15) === " ";
479 * getLineIndent("first\n second\n",5) === " ";
480 * getLineIndent("first\n second\n",4) === "";
481 * getLineIndent(" first\n second\n",6) === " ";
482 * </pre>
483 */
484 public static String getLineIndent(String line, int pos) {
485 int p = indexOfBack(line, "\n", pos);
486 int e = p+1;
487 while ( e < line.length() && Character.isWhitespace(line.charAt(e)) ) e++;
488 return line.substring(p+1,e);
489 }
490
491 /**
492 * Check if string is empty
493 * @param s string to check
494 * @return true if null or just spaces or tabs, false in other case
495 * @example
496 * <pre name="test">
497 * isEmpty(null) === true;
498 * isEmpty("") === true;
499 * isEmpty(" ") === true;
500 * isEmpty("a") === false;
501 * isEmpty("\n") === false;
502 * </pre>
503 */
504 public static boolean isEmpty(String s) {
505 if (s == null) return true;
506 for (int i=0; i<s.length(); i++ ) {
507 char c = s.charAt(i);
508 if ( c != ' ' && c != '\t' ) return false;
509 }
510 return true;
511 }
512
513 }
514