欢迎访问宙启技术站
智能推送

Java函数如何实现对字符串的截取

发布时间:2023-06-25 10:35:50

以下是一个Java函数,实现对字符串的截取1000字的功能:

public static String truncateString(String str) {
    if (str.length() <= 1000) {
        return str;
    }
    return str.substring(0, 1000);
}

该函数接收一个字符串参数str,如果str的长度小于或等于1000,则直接返回str原样;否则,使用substring()函数从str的第0个字符开始截取1000个字符,并返回截取后的字符串。

例如,对于输入字符串"This is a very long string that needs to be truncated to 1000 characters for example purposes.",该函数返回的字符串为"This is a very long string that needs to be truncated to 1000 characters for example purposes."(因为该字符串长度小于1000);对于输入字符串"This is a very long string that needs to be truncated to 1000 characters for example purposes. This is more text that should be truncated.",该函数返回的字符串为"This is a very long string that needs to be truncated to 1000 characters for example purposes. This is more text that should be truncated."(因为该字符串长度大于1000,被截取前1000个字符)。