StringUtil.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import PrintStream from '../../../../java/io/PrintStream'
  2. import StringReader from '../../../../java/io/StringReader'
  3. import System from '../../../../java/lang/System'
  4. import ArrayList from '../../../../java/util/ArrayList'
  5. import ByteArrayOutputStream from '../../../../java/io/ByteArrayOutputStream'
  6. import Assert from './Assert'
  7. import IOException from '../../../../java/io/IOException'
  8. import LineNumberReader from '../../../../java/io/LineNumberReader'
  9. export default class StringUtil {
  10. static chars(c, n) {
  11. const ch = new Array(n).fill(null)
  12. for (let i = 0; i < n; i++)
  13. ch[i] = c
  14. return new String(ch)
  15. }
  16. static getStackTrace() {
  17. if (arguments.length === 1) {
  18. const t = arguments[0]
  19. const os = new ByteArrayOutputStream()
  20. const ps = new PrintStream(os)
  21. t.printStackTrace(ps)
  22. return os.toString()
  23. } else if (arguments.length === 2) {
  24. const t = arguments[0], depth = arguments[1]
  25. let stackTrace = ''
  26. const stringReader = new StringReader(StringUtil.getStackTrace(t))
  27. const lineNumberReader = new LineNumberReader(stringReader)
  28. for (let i = 0; i < depth; i++)
  29. try {
  30. stackTrace += lineNumberReader.readLine() + StringUtil.NEWLINE
  31. } catch (e) {
  32. if (e instanceof IOException)
  33. Assert.shouldNeverReachHere()
  34. else throw e
  35. } finally {}
  36. return stackTrace
  37. }
  38. }
  39. static spaces(n) {
  40. return StringUtil.chars(' ', n)
  41. }
  42. static split(s, separator) {
  43. const separatorlen = separator.length
  44. const tokenList = new ArrayList()
  45. let tmpString = '' + s
  46. let pos = tmpString.indexOf(separator)
  47. while (pos >= 0) {
  48. const token = tmpString.substring(0, pos)
  49. tokenList.add(token)
  50. tmpString = tmpString.substring(pos + separatorlen)
  51. pos = tmpString.indexOf(separator)
  52. }
  53. if (tmpString.length > 0) tokenList.add(tmpString)
  54. const res = new Array(tokenList.size()).fill(null)
  55. for (let i = 0; i < res.length; i++)
  56. res[i] = tokenList.get(i)
  57. return res
  58. }
  59. }
  60. StringUtil.NEWLINE = System.getProperty('line.separator')