在Java中手动修剪字符串(不带String.trim())

时间:2017-01-08 04:55:08

标签: java string trim

我正在尝试不使用// com.alibaba.fastjson String res = o.getJSONArray("results").getJSONObject(0).getJSONObject("name").getString("title"); System.out.println(res); out:# mr 这样做的想法。我创建了一个修剪前导和尾随空格的方法,如下所示:

String.trim()

我已经对它进行了测试,它的工作效率为100%。但是,我不相信这是最有效或最实际的实施方案。我怎么能这样做呢?我觉得可以在不使用额外变量public static String removeLeadingAndTrailingSpaces(String s) { StringBuilder sb = new StringBuilder(); int i = 0; while (s.charAt(i) == ' ') { i++; } for (; i < s.length(); i++) { sb.append(s.charAt(i)); } // aux is the string with only leading spaces removed String aux = sb.toString(); int j = aux.length() - 1; while (aux.charAt(j) == ' ') { j--; } // now both leading and trailing spaces have been removed String result = aux.substring(0, j + 1); return result; } aux的情况下完成,但我无法想出办法。

2 个答案:

答案 0 :(得分:3)

从末尾检查s以确定尾随空格的开始位置并返回s的子字符串。无需sbaux

public static String removeLeadingAndTrailingSpaces(String s) {
    int end = s.length();
    int i = 0;

    while (i < end && s.charAt(i) == ' ') {
        i++;
    }

    while (end > i && s.charAt(end - 1) == ' ') {
        end--;
    }

    return end> i ? s.substring(i, end) : "";
}

要更接近trim(),您需要检查所有空格字符,而不只是' '

答案 1 :(得分:0)

如需移除空间,请使用 myString.replace(&#34;&#34;,&#34;&#34;);

谢谢和问候, Dilip D