MATSIM
StringUtils.java
Go to the documentation of this file.
1 /* *********************************************************************** *
2  * project: org.matsim.*
3  * StringUtils.java
4  * *
5  * *********************************************************************** *
6  * *
7  * copyright : (C) 2007 by the members listed in the COPYING, *
8  * LICENSE and WARRANTY file. *
9  * email : info at matsim dot org *
10  * *
11  * *********************************************************************** *
12  * *
13  * This program is free software; you can redistribute it and/or modify *
14  * it under the terms of the GNU General Public License as published by *
15  * the Free Software Foundation; either version 2 of the License, or *
16  * (at your option) any later version. *
17  * See also COPYING, LICENSE and WARRANTY file *
18  * *
19  * *********************************************************************** */
20 
21 package org.matsim.core.utils.misc;
22 
28 public class StringUtils {
29 
54  public static String[] explode(final String str, final char delimiter, final int limit) {
55  int count = 0;
56  int len = str.length();
57  int maxPos = 0; // the position of the last non-delimiter char in the string
58  int countAtMaxPos = 0;
59  int upperLimit = limit-1;
60  // count how often the delimiter occurs in the string
61  for (int pos = 0; pos < len; pos++) {
62  if ((str.charAt(pos) == delimiter) && (limit == 0 || count < upperLimit)) {
63  count++;
64  } else {
65  maxPos = pos;
66  countAtMaxPos = count;
67  }
68  }
69 
70  if (count == 0) {
71  String[] parts = new String[1];
72  parts[0] = str;
73  return parts;
74  }
75 
76  // create a big enough array to hold the result
77  String[] parts = new String[countAtMaxPos + 1];
78  int startPos = 0;
79  count = 0;
80  // loop once through the string and always take the substrings between the delimiters
81  for (int pos = 0; pos < maxPos; pos++) {
82  if ((str.charAt(pos) == delimiter) && (limit == 0 || count < upperLimit)) {
83  parts[count] = str.substring(startPos, pos);
84  startPos = pos + 1;
85  count++;
86  }
87  }
88  /* Add the final part ended by the string, not by a delimiter, to our list.
89  * There is always a final part because of the way maxPos and countAtMaxPos
90  * are derived: maxPos points to a non-delimiter. This means there is always
91  * at least one character between the last delimiter and maxPos, and that's
92  * the part we are still missing... so add it! */
93  parts[count] = str.substring(startPos, maxPos+1);
94 
95  return parts;
96  }
97 
112  public static String[] explode(final String str, final char delimiter) {
113  return explode(str, delimiter, 0);
114  }
115 }
static String [] explode(final String str, final char delimiter)
static String [] explode(final String str, final char delimiter, final int limit)