You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StringUtil.java 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.util;
  16. import static java.nio.charset.StandardCharsets.ISO_8859_1;
  17. import java.nio.charset.Charset;
  18. import java.nio.charset.StandardCharsets;
  19. import java.util.Locale;
  20. /**
  21. * Collection of string handling utilities
  22. */
  23. @Internal
  24. public final class StringUtil {
  25. //arbitrarily selected; may need to increase
  26. private static final int MAX_RECORD_LENGTH = 10000000;
  27. public static final Charset UTF16LE = StandardCharsets.UTF_16LE;
  28. public static final Charset UTF8 = StandardCharsets.UTF_8;
  29. public static final Charset WIN_1252 = Charset.forName("cp1252");
  30. private StringUtil() {
  31. // no instances of this class
  32. }
  33. /**
  34. * Given a byte array of 16-bit unicode characters in Little Endian
  35. * format (most important byte last), return a Java String representation
  36. * of it.
  37. * <p>
  38. * { 0x16, 0x00 } -0x16
  39. *
  40. * @param string the byte array to be converted
  41. * @param offset the initial offset into the
  42. * byte array. it is assumed that string[ offset ] and string[ offset +
  43. * 1 ] contain the first 16-bit unicode character
  44. * @param len the length of the final string
  45. * @return the converted string, never {@code null}.
  46. * @throws ArrayIndexOutOfBoundsException if offset is out of bounds for
  47. * the byte array (i.e., is negative or is greater than or equal to
  48. * string.length)
  49. * @throws IllegalArgumentException if len is too large (i.e.,
  50. * there is not enough data in string to create a String of that
  51. * length)
  52. */
  53. public static String getFromUnicodeLE(
  54. final byte[] string,
  55. final int offset,
  56. final int len)
  57. throws ArrayIndexOutOfBoundsException, IllegalArgumentException {
  58. if (len == 0) {
  59. return "";
  60. }
  61. if ((offset < 0) || (offset >= string.length)) {
  62. throw new ArrayIndexOutOfBoundsException("Illegal offset " + offset + " (String data is of length " + string.length + ")");
  63. }
  64. if ((len < 0) || (((string.length - offset) / 2) < len)) {
  65. throw new IllegalArgumentException("Illegal length " + len);
  66. }
  67. return new String(string, offset, len * 2, UTF16LE);
  68. }
  69. /**
  70. * Given a byte array of 16-bit unicode characters in little endian
  71. * format (most important byte last), return a Java String representation
  72. * of it.
  73. * <p>
  74. * { 0x16, 0x00 } -0x16
  75. *
  76. * @param string the byte array to be converted
  77. * @return the converted string, never {@code null}
  78. */
  79. public static String getFromUnicodeLE(byte[] string) {
  80. if (string.length == 0) {
  81. return "";
  82. }
  83. return getFromUnicodeLE(string, 0, string.length / 2);
  84. }
  85. /**
  86. * Convert String to 16-bit unicode characters in little endian format
  87. *
  88. * @param string the string
  89. * @return the byte array of 16-bit unicode characters
  90. */
  91. public static byte[] getToUnicodeLE(String string) {
  92. return string.getBytes(UTF16LE);
  93. }
  94. /**
  95. * Read 8 bit data (in ISO-8859-1 codepage) into a (unicode) Java
  96. * String and return.
  97. * (In Excel terms, read compressed 8 bit unicode as a string)
  98. *
  99. * @param string byte array to read
  100. * @param offset offset to read byte array
  101. * @param len length to read byte array
  102. * @return String generated String instance by reading byte array
  103. */
  104. public static String getFromCompressedUnicode(
  105. final byte[] string,
  106. final int offset,
  107. final int len) {
  108. int len_to_use = Math.min(len, string.length - offset);
  109. return new String(string, offset, len_to_use, ISO_8859_1);
  110. }
  111. public static String readCompressedUnicode(LittleEndianInput in, int nChars) {
  112. byte[] buf = IOUtils.safelyAllocate(nChars, MAX_RECORD_LENGTH);
  113. in.readFully(buf);
  114. return new String(buf, ISO_8859_1);
  115. }
  116. /**
  117. * InputStream {@code in} is expected to contain:
  118. * <ol>
  119. * <li>ushort nChars</li>
  120. * <li>byte is16BitFlag</li>
  121. * <li>byte[]/char[] characterData</li>
  122. * </ol>
  123. * For this encoding, the is16BitFlag is always present even if nChars==0.
  124. * <p>
  125. * This structure is also known as a XLUnicodeString.
  126. */
  127. public static String readUnicodeString(LittleEndianInput in) {
  128. int nChars = in.readUShort();
  129. byte flag = in.readByte();
  130. if ((flag & 0x01) == 0) {
  131. return readCompressedUnicode(in, nChars);
  132. }
  133. return readUnicodeLE(in, nChars);
  134. }
  135. /**
  136. * InputStream {@code in} is expected to contain:
  137. * <ol>
  138. * <li>byte is16BitFlag</li>
  139. * <li>byte[]/char[] characterData</li>
  140. * </ol>
  141. * For this encoding, the is16BitFlag is always present even if nChars==0.
  142. * <br>
  143. * This method should be used when the nChars field is <em>not</em> stored
  144. * as a ushort immediately before the is16BitFlag. Otherwise, {@link
  145. * #readUnicodeString(LittleEndianInput)} can be used.
  146. */
  147. public static String readUnicodeString(LittleEndianInput in, int nChars) {
  148. byte is16Bit = in.readByte();
  149. if ((is16Bit & 0x01) == 0) {
  150. return readCompressedUnicode(in, nChars);
  151. }
  152. return readUnicodeLE(in, nChars);
  153. }
  154. /**
  155. * OutputStream {@code out} will get:
  156. * <ol>
  157. * <li>ushort nChars</li>
  158. * <li>byte is16BitFlag</li>
  159. * <li>byte[]/char[] characterData</li>
  160. * </ol>
  161. * For this encoding, the is16BitFlag is always present even if nChars==0.
  162. */
  163. public static void writeUnicodeString(LittleEndianOutput out, String value) {
  164. int nChars = value.length();
  165. out.writeShort(nChars);
  166. boolean is16Bit = hasMultibyte(value);
  167. out.writeByte(is16Bit ? 0x01 : 0x00);
  168. if (is16Bit) {
  169. putUnicodeLE(value, out);
  170. } else {
  171. putCompressedUnicode(value, out);
  172. }
  173. }
  174. /**
  175. * OutputStream {@code out} will get:
  176. * <ol>
  177. * <li>byte is16BitFlag</li>
  178. * <li>byte[]/char[] characterData</li>
  179. * </ol>
  180. * For this encoding, the is16BitFlag is always present even if nChars==0.
  181. * <br>
  182. * This method should be used when the nChars field is <em>not</em> stored
  183. * as a ushort immediately before the is16BitFlag. Otherwise, {@link
  184. * #writeUnicodeString(LittleEndianOutput, String)} can be used.
  185. */
  186. public static void writeUnicodeStringFlagAndData(LittleEndianOutput out, String value) {
  187. boolean is16Bit = hasMultibyte(value);
  188. out.writeByte(is16Bit ? 0x01 : 0x00);
  189. if (is16Bit) {
  190. putUnicodeLE(value, out);
  191. } else {
  192. putCompressedUnicode(value, out);
  193. }
  194. }
  195. /**
  196. * @return the number of bytes that would be written by {@link #writeUnicodeString(LittleEndianOutput, String)}
  197. */
  198. public static int getEncodedSize(String value) {
  199. int result = 2 + 1;
  200. result += value.length() * (StringUtil.hasMultibyte(value) ? 2 : 1);
  201. return result;
  202. }
  203. /**
  204. * Takes a unicode (java) string, and returns it as 8 bit data (in ISO-8859-1
  205. * codepage).
  206. * (In Excel terms, write compressed 8 bit unicode)
  207. *
  208. * @param input the String containing the data to be written
  209. * @param output the byte array to which the data is to be written
  210. * @param offset an offset into the byte arrat at which the data is start
  211. * when written
  212. */
  213. public static void putCompressedUnicode(String input, byte[] output, int offset) {
  214. byte[] bytes = input.getBytes(ISO_8859_1);
  215. System.arraycopy(bytes, 0, output, offset, bytes.length);
  216. }
  217. public static void putCompressedUnicode(String input, LittleEndianOutput out) {
  218. byte[] bytes = input.getBytes(ISO_8859_1);
  219. out.write(bytes);
  220. }
  221. /**
  222. * Takes a unicode string, and returns it as little endian (most
  223. * important byte last) bytes in the supplied byte array.
  224. * (In Excel terms, write uncompressed unicode)
  225. *
  226. * @param input the String containing the unicode data to be written
  227. * @param output the byte array to hold the uncompressed unicode, should be twice the length of the String
  228. * @param offset the offset to start writing into the byte array
  229. */
  230. public static void putUnicodeLE(String input, byte[] output, int offset) {
  231. byte[] bytes = input.getBytes(UTF16LE);
  232. System.arraycopy(bytes, 0, output, offset, bytes.length);
  233. }
  234. public static void putUnicodeLE(String input, LittleEndianOutput out) {
  235. byte[] bytes = input.getBytes(UTF16LE);
  236. out.write(bytes);
  237. }
  238. public static String readUnicodeLE(LittleEndianInput in, int nChars) {
  239. byte[] bytes = IOUtils.safelyAllocate(nChars * 2L, MAX_RECORD_LENGTH);
  240. in.readFully(bytes);
  241. return new String(bytes, UTF16LE);
  242. }
  243. /**
  244. * @return the encoding we want to use, currently hardcoded to ISO-8859-1
  245. */
  246. public static String getPreferredEncoding() {
  247. return ISO_8859_1.name();
  248. }
  249. /**
  250. * check the parameter has multibyte character
  251. *
  252. * @param value string to check
  253. * @return boolean result true:string has at least one multibyte character
  254. */
  255. public static boolean hasMultibyte(String value) {
  256. if (value == null) {
  257. return false;
  258. }
  259. for (char c : value.toCharArray()) {
  260. if (c > 0xFF) {
  261. return true;
  262. }
  263. }
  264. return false;
  265. }
  266. /**
  267. * Tests if the string starts with the specified prefix, ignoring case consideration.
  268. */
  269. public static boolean startsWithIgnoreCase(String haystack, String prefix) {
  270. return haystack.regionMatches(true, 0, prefix, 0, prefix.length());
  271. }
  272. /**
  273. * Tests if the string ends with the specified suffix, ignoring case consideration.
  274. */
  275. public static boolean endsWithIgnoreCase(String haystack, String suffix) {
  276. int length = suffix.length();
  277. int start = haystack.length() - length;
  278. return haystack.regionMatches(true, start, suffix, 0, length);
  279. }
  280. @Internal
  281. public static String toLowerCase(char c) {
  282. return Character.toString(c).toLowerCase(Locale.ROOT);
  283. }
  284. @Internal
  285. public static String toUpperCase(char c) {
  286. return Character.toString(c).toUpperCase(Locale.ROOT);
  287. }
  288. @Internal
  289. public static boolean isUpperCase(char c) {
  290. String s = Character.toString(c);
  291. return s.toUpperCase(Locale.ROOT).equals(s);
  292. }
  293. /**
  294. * Some strings may contain encoded characters of the unicode private use area.
  295. * Currently the characters of the symbol fonts are mapped to the corresponding
  296. * characters in the normal unicode range.
  297. *
  298. * @param string the original string
  299. * @return the string with mapped characters
  300. * @see <a href="http://www.alanwood.net/unicode/private_use_area.html#symbol">Private Use Area (symbol)</a>
  301. * @see <a href="http://www.alanwood.net/demos/symbol.html">Symbol font - Unicode alternatives for Greek and special characters in HTML</a>
  302. */
  303. public static String mapMsCodepointString(String string) {
  304. if (string == null || string.isEmpty()) {
  305. return string;
  306. }
  307. int[] cps = string.codePoints().map(StringUtil::mapMsCodepoint).toArray();
  308. return new String(cps, 0, cps.length);
  309. }
  310. private static int mapMsCodepoint(int cp) {
  311. if (0xf020 <= cp && cp <= 0xf07f) {
  312. return symbolMap_f020[cp - 0xf020];
  313. } else if (0xf0a0 <= cp && cp <= 0xf0ff) {
  314. return symbolMap_f0a0[cp - 0xf0a0];
  315. }
  316. return cp;
  317. }
  318. private static final int[] symbolMap_f020 = {
  319. ' ', // 0xf020 space
  320. '!', // 0xf021 exclam
  321. 8704, // 0xf022 universal
  322. '#', // 0xf023 numbersign
  323. 8707, // 0xf024 existential
  324. '%', // 0xf025 percent
  325. '&', // 0xf026 ampersand
  326. 8717, // 0xf027 suchthat
  327. '(', // 0xf028 parenleft
  328. ')', // 0xf029 parentright
  329. 8727, // 0xf02a asteriskmath
  330. '+', // 0xf02b plus
  331. ',', // 0xf02c comma
  332. 8722, // 0xf02d minus sign (long -)
  333. '.', // 0xf02e period
  334. '/', // 0xf02f slash
  335. '0', // 0xf030 0
  336. '1', // 0xf031 1
  337. '2', // 0xf032 2
  338. '3', // 0xf033 3
  339. '4', // 0xf034 4
  340. '5', // 0xf035 5
  341. '6', // 0xf036 6
  342. '7', // 0xf037 7
  343. '8', // 0xf038 8
  344. '9', // 0xf039 9
  345. ':', // 0xf03a colon
  346. ';', // 0xf03b semicolon
  347. '<', // 0xf03c less
  348. '=', // 0xf03d equal
  349. '>', // 0xf03e greater
  350. '?', // 0xf03f question
  351. 8773, // 0xf040 congruent
  352. 913, // 0xf041 alpha (upper)
  353. 914, // 0xf042 beta (upper)
  354. 935, // 0xf043 chi (upper)
  355. 916, // 0xf044 delta (upper)
  356. 917, // 0xf045 epsilon (upper)
  357. 934, // 0xf046 phi (upper)
  358. 915, // 0xf047 gamma (upper)
  359. 919, // 0xf048 eta (upper)
  360. 921, // 0xf049 iota (upper)
  361. 977, // 0xf04a theta1 (lower)
  362. 922, // 0xf04b kappa (upper)
  363. 923, // 0xf04c lambda (upper)
  364. 924, // 0xf04d mu (upper)
  365. 925, // 0xf04e nu (upper)
  366. 927, // 0xf04f omicron (upper)
  367. 928, // 0xf050 pi (upper)
  368. 920, // 0xf051 theta (upper)
  369. 929, // 0xf052 rho (upper)
  370. 931, // 0xf053 sigma (upper)
  371. 932, // 0xf054 tau (upper)
  372. 933, // 0xf055 upsilon (upper)
  373. 962, // 0xf056 simga1 (lower)
  374. 937, // 0xf057 omega (upper)
  375. 926, // 0xf058 xi (upper)
  376. 936, // 0xf059 psi (upper)
  377. 918, // 0xf05a zeta (upper)
  378. '[', // 0xf05b bracketleft
  379. 8765, // 0xf05c therefore
  380. ']', // 0xf05d bracketright
  381. 8869, // 0xf05e perpendicular
  382. '_', // 0xf05f underscore
  383. ' ', // 0xf060 radicalex (doesn't exist in unicode)
  384. 945, // 0xf061 alpha (lower)
  385. 946, // 0xf062 beta (lower)
  386. 967, // 0xf063 chi (lower)
  387. 948, // 0xf064 delta (lower)
  388. 949, // 0xf065 epsilon (lower)
  389. 966, // 0xf066 phi (lower)
  390. 947, // 0xf067 gamma (lower)
  391. 951, // 0xf068 eta (lower)
  392. 953, // 0xf069 iota (lower)
  393. 981, // 0xf06a phi1 (lower)
  394. 954, // 0xf06b kappa (lower)
  395. 955, // 0xf06c lambda (lower)
  396. 956, // 0xf06d mu (lower)
  397. 957, // 0xf06e nu (lower)
  398. 959, // 0xf06f omnicron (lower)
  399. 960, // 0xf070 pi (lower)
  400. 952, // 0xf071 theta (lower)
  401. 961, // 0xf072 rho (lower)
  402. 963, // 0xf073 sigma (lower)
  403. 964, // 0xf074 tau (lower)
  404. 965, // 0xf075 upsilon (lower)
  405. 982, // 0xf076 piv (lower)
  406. 969, // 0xf077 omega (lower)
  407. 958, // 0xf078 xi (lower)
  408. 968, // 0xf079 psi (lower)
  409. 950, // 0xf07a zeta (lower)
  410. '{', // 0xf07b braceleft
  411. '|', // 0xf07c bar
  412. '}', // 0xf07d braceright
  413. 8764, // 0xf07e similar '~'
  414. ' ', // 0xf07f not defined
  415. };
  416. private static final int[] symbolMap_f0a0 = {
  417. 8364, // 0xf0a0 not defined / euro symbol
  418. 978, // 0xf0a1 upsilon1 (upper)
  419. 8242, // 0xf0a2 minute
  420. 8804, // 0xf0a3 lessequal
  421. 8260, // 0xf0a4 fraction
  422. 8734, // 0xf0a5 infinity
  423. 402, // 0xf0a6 florin
  424. 9827, // 0xf0a7 club
  425. 9830, // 0xf0a8 diamond
  426. 9829, // 0xf0a9 heart
  427. 9824, // 0xf0aa spade
  428. 8596, // 0xf0ab arrowboth
  429. 8591, // 0xf0ac arrowleft
  430. 8593, // 0xf0ad arrowup
  431. 8594, // 0xf0ae arrowright
  432. 8595, // 0xf0af arrowdown
  433. 176, // 0xf0b0 degree
  434. 177, // 0xf0b1 plusminus
  435. 8243, // 0xf0b2 second
  436. 8805, // 0xf0b3 greaterequal
  437. 215, // 0xf0b4 multiply
  438. 181, // 0xf0b5 proportional
  439. 8706, // 0xf0b6 partialdiff
  440. 8729, // 0xf0b7 bullet
  441. 247, // 0xf0b8 divide
  442. 8800, // 0xf0b9 notequal
  443. 8801, // 0xf0ba equivalence
  444. 8776, // 0xf0bb approxequal
  445. 8230, // 0xf0bc ellipsis
  446. 9168, // 0xf0bd arrowvertex
  447. 9135, // 0xf0be arrowhorizex
  448. 8629, // 0xf0bf carriagereturn
  449. 8501, // 0xf0c0 aleph
  450. 8475, // 0xf0c1 Ifraktur
  451. 8476, // 0xf0c2 Rfraktur
  452. 8472, // 0xf0c3 weierstrass
  453. 8855, // 0xf0c4 circlemultiply
  454. 8853, // 0xf0c5 circleplus
  455. 8709, // 0xf0c6 emptyset
  456. 8745, // 0xf0c7 intersection
  457. 8746, // 0xf0c8 union
  458. 8835, // 0xf0c9 propersuperset
  459. 8839, // 0xf0ca reflexsuperset
  460. 8836, // 0xf0cb notsubset
  461. 8834, // 0xf0cc propersubset
  462. 8838, // 0xf0cd reflexsubset
  463. 8712, // 0xf0ce element
  464. 8713, // 0xf0cf notelement
  465. 8736, // 0xf0d0 angle
  466. 8711, // 0xf0d1 gradient
  467. 174, // 0xf0d2 registerserif
  468. 169, // 0xf0d3 copyrightserif
  469. 8482, // 0xf0d4 trademarkserif
  470. 8719, // 0xf0d5 product
  471. 8730, // 0xf0d6 radical
  472. 8901, // 0xf0d7 dotmath
  473. 172, // 0xf0d8 logicalnot
  474. 8743, // 0xf0d9 logicaland
  475. 8744, // 0xf0da logicalor
  476. 8660, // 0xf0db arrowdblboth
  477. 8656, // 0xf0dc arrowdblleft
  478. 8657, // 0xf0dd arrowdblup
  479. 8658, // 0xf0de arrowdblright
  480. 8659, // 0xf0df arrowdbldown
  481. 9674, // 0xf0e0 lozenge
  482. 9001, // 0xf0e1 angleleft
  483. 174, // 0xf0e2 registersans
  484. 169, // 0xf0e3 copyrightsans
  485. 8482, // 0xf0e4 trademarksans
  486. 8721, // 0xf0e5 summation
  487. 9115, // 0xf0e6 parenlefttp
  488. 9116, // 0xf0e7 parenleftex
  489. 9117, // 0xf0e8 parenleftbt
  490. 9121, // 0xf0e9 bracketlefttp
  491. 9122, // 0xf0ea bracketleftex
  492. 9123, // 0xf0eb bracketleftbt
  493. 9127, // 0xf0ec bracelefttp
  494. 9128, // 0xf0ed braceleftmid
  495. 9129, // 0xf0ee braceleftbt
  496. 9130, // 0xf0ef braceex
  497. ' ', // 0xf0f0 not defined
  498. 9002, // 0xf0f1 angleright
  499. 8747, // 0xf0f2 integral
  500. 8992, // 0xf0f3 integraltp
  501. 9134, // 0xf0f4 integralex
  502. 8993, // 0xf0f5 integralbt
  503. 9118, // 0xf0f6 parenrighttp
  504. 9119, // 0xf0f7 parenrightex
  505. 9120, // 0xf0f8 parenrightbt
  506. 9124, // 0xf0f9 bracketrighttp
  507. 9125, // 0xf0fa bracketrightex
  508. 9126, // 0xf0fb bracketrightbt
  509. 9131, // 0xf0fc bracerighttp
  510. 9132, // 0xf0fd bracerightmid
  511. 9133, // 0xf0fe bracerightbt
  512. ' ', // 0xf0ff not defined
  513. };
  514. // Could be replaced with org.apache.commons.lang3.StringUtils#join
  515. @Internal
  516. public static String join(Object[] array, String separator) {
  517. if (array == null || array.length == 0) {
  518. return "";
  519. }
  520. StringBuilder sb = new StringBuilder();
  521. sb.append(array[0]);
  522. for (int i = 1; i < array.length; i++) {
  523. sb.append(separator).append(array[i]);
  524. }
  525. return sb.toString();
  526. }
  527. @Internal
  528. public static String join(Object[] array) {
  529. if (array == null) {
  530. return "";
  531. }
  532. StringBuilder sb = new StringBuilder();
  533. for (Object o : array) {
  534. sb.append(o);
  535. }
  536. return sb.toString();
  537. }
  538. @Internal
  539. public static String join(String separator, Object... array) {
  540. return join(array, separator);
  541. }
  542. /**
  543. * Count number of occurrences of needle in haystack
  544. * Has same signature as org.apache.commons.lang3.StringUtils#countMatches
  545. *
  546. * @param haystack the CharSequence to check, may be null
  547. * @param needle the character to count the quantity of
  548. * @return the number of occurrences, 0 if the CharSequence is null
  549. */
  550. public static int countMatches(CharSequence haystack, char needle) {
  551. if (haystack == null) {
  552. return 0;
  553. }
  554. int count = 0;
  555. final int length = haystack.length();
  556. for (int i = 0; i < length; i++) {
  557. if (haystack.charAt(i) == needle) {
  558. count++;
  559. }
  560. }
  561. return count;
  562. }
  563. /**
  564. * Given a byte array of 16-bit unicode characters in Little Endian
  565. * format (most important byte last), return a Java String representation
  566. * of it.
  567. *
  568. * Scans the byte array for two continous 0 bytes and returns the string before.
  569. * <p>
  570. *
  571. * #61881: there seem to be programs out there, which write the 0-termination also
  572. * at the beginning of the string. Check if the next two bytes contain a valid ascii char
  573. * and correct the _recdata with a '?' char
  574. *
  575. *
  576. * @param string the byte array to be converted
  577. * @param offset the initial offset into the
  578. * byte array. it is assumed that string[ offset ] and string[ offset +
  579. * 1 ] contain the first 16-bit unicode character
  580. * @param len the max. length of the final string
  581. * @return the converted string, never {@code null}.
  582. * @throws ArrayIndexOutOfBoundsException if offset is out of bounds for
  583. * the byte array (i.e., is negative or is greater than or equal to
  584. * string.length)
  585. * @throws IllegalArgumentException if len is too large (i.e.,
  586. * there is not enough data in string to create a String of that
  587. * length)
  588. */
  589. public static String getFromUnicodeLE0Terminated(
  590. final byte[] string,
  591. final int offset,
  592. final int len)
  593. throws ArrayIndexOutOfBoundsException, IllegalArgumentException {
  594. if ((offset < 0) || (offset >= string.length)) {
  595. throw new ArrayIndexOutOfBoundsException("Illegal offset " + offset + " (String data is of length " + string.length + ")");
  596. }
  597. if ((len < 0) || (((string.length - offset) / 2) < len)) {
  598. throw new IllegalArgumentException("Illegal length " + len);
  599. }
  600. final int newOffset;
  601. final int newMaxLen;
  602. final String prefix;
  603. // #61881 - for now we only check the first char
  604. if (len > 0 && offset < (string.length - 1) && string[offset] == 0 && string[offset+1] == 0) {
  605. newOffset = offset+2;
  606. prefix = "?";
  607. // check if the next char is garbage and limit the len if necessary
  608. final int cp = (len > 1) ? LittleEndian.getShort(string, offset+2) : 0;
  609. newMaxLen = Character.isJavaIdentifierPart(cp) ? len-1 : 0;
  610. } else {
  611. newOffset = offset;
  612. prefix = "";
  613. newMaxLen = len;
  614. }
  615. int newLen = 0;
  616. // loop until we find a null-terminated end
  617. for(; newLen < newMaxLen; newLen++) {
  618. if (string[newOffset + newLen * 2] == 0 && string[newOffset + newLen * 2 + 1] == 0) {
  619. break;
  620. }
  621. }
  622. newLen = Math.min(newLen, newMaxLen);
  623. return prefix + ((newLen == 0) ? "" : new String(string, newOffset, newLen * 2, UTF16LE));
  624. }
  625. }