【问题标题】:Doing isEmpty, split, contains and replace manually手动执行 isEmpty、拆分、包含和替换
【发布时间】:2012-10-17 18:12:47
【问题描述】:

所以我正在开发一个项目,由于某些原因仅限于 java squawk 1.4。因此,String 类不包含标题中的四个方法。我的程序中需要这些方法,并得出结论,我必须创建一个 Util 类来自行执行这些方法的功能。

首先,这是否存在于某个地方?显然,我的第一反应是考虑从 String 类中复制源代码,但是这些方法的依赖关系太深了,我无法使用。

其次,我无法复制 split(String regex)replace(CharSequence target, CharSequence replacement) 的行为。 contains(String)isEmpty() 显然很容易,但我在编写其他代码时遇到了麻烦。

现在,我有 split 工作(虽然它的工作方式与 jdk 7 中的不同,我不想得到错误)。

public static String[] split(String string, char split) {
    String[] s = new String[0];
    int count = 0;
    for (int x = 0; x < string.length(); x++) {
        if (string.charAt(x) == split) {
            String[] tmp = s;
            s = new String[++count];
            System.arraycopy(tmp, 0, s, 0, tmp.length);
            s[count - 1] = string.substring(x).substring(1);
            if (contains(s[count - 1], split + "")) {
                s[count - 1] = s[count - 1].substring(0, s[count - 1].indexOf(split));
            }
        }
    }
    return s.length == 0 ? new String[]{string} : s;
}

Replace 更难做到,我已经尝试了好几个小时。这似乎是 google/archives 从未尝试过的问题。

【问题讨论】:

  • String.split(String regex) 存在于 Java 1.4 中...您确定需要重新实现它吗? (诚​​然,我对 Squawk 一无所知。)
  • @JonSkeet 是的,我正在使用一种叫做 sun squawk 的东西,它在 String 类中不存在。
  • 您能否提供关于可用的参考资料?如果它不能简单地匹配 JDK 版本,那么提供替代实现将更加困难......
  • @JonSkeet 哦,当然,wbrobotics.com/javadoc/overview-summary.html 是我们所有可用类/方法的 javadocs。
  • @LouisWasserman i.imgur.com/suwdb.png 不完全是 1.4,也不是 2。这是一个实现。

标签: java regex string replace split


【解决方案1】:

制作方法...

public static boolean isEmpty(String string) {
    return string.length() == 0;
}

public static String[] split(String string, char split) {
    return _split(new String[0], string, split);
}

private static String[] _split(String[] current, String string, char split) {
    if (isEmpty(string)) {
        return current;
    }
    String[] tmp = current;
    current = new String[tmp.length + 1];
    System.arraycopy(tmp, 0, current, 0, tmp.length);
    if (contains(string, split + "")) {
        current[current.length - 1] = string.substring(0, string.indexOf(split));
        string = string.substring(string.indexOf(split) + 1);
    } else {
        current[current.length - 1] = string;
        string = "";
    }
    return _split(current, string, split);
}

public static boolean contains(String string, String contains) {
    return string.indexOf(contains) > -1;
}

public static String replace(String string, char replace, String replacement) {
    String[] s = split(string, replace);

    String tmp = "";
    for (int x = 0; x < s.length; x++) {
        if (contains(s[x], replace + "")) {
            tmp += s[x].substring(1);
        } else {
            tmp += s[x];
        }
    }
    return tmp;
}

【讨论】:

    猜你喜欢
    • 2013-01-05
    • 1970-01-01
    • 2016-02-15
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 2020-05-25
    • 2016-03-07
    相关资源
    最近更新 更多