Java 删除 String 的后面的若干字符的实现

该实现的代码如下:

    private String chop(final String sourceString, final int length) {
        if (!sourceString.isEmpty()) {
            if (sourceString.length() > length) {
                return sourceString.substring(0, sourceString.length() - length);
            }
            return "";
        }
        return sourceString;
    }

该实现在 Android Studio 中的测试代码如下:

        String testStr = "I am toby!";
        Log.d(TAG, "testStr length: " + testStr.length());
        Log.d(TAG, "testStr content: " + testStr);
        testStr = chop(testStr, 1);
        Log.d(TAG, "testStr chop 1 content: " + testStr);

        Log.d(TAG, "testStr length: " + testStr.length());
        Log.d(TAG, "testStr content: " + testStr);
        testStr = chop(testStr, 10);
        Log.d(TAG, "testStr length: " + testStr.length());
        Log.d(TAG, "testStr chop 10 content: " + testStr);

运行输出结果:

《Java 删除 String 的后面的若干字符的实现》 运行输出结果

    原文作者:赵者也
    原文地址: https://www.jianshu.com/p/9e6a343a1d9b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞