Android 成长笔记

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

2017-10-19  本文已影响6人  赵者也

该实现的代码如下:

    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);

运行输出结果:

运行输出结果
上一篇下一篇

猜你喜欢

热点阅读