该实现的代码如下:
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);
运行输出结果: