lastIndexOf和subString的使用

lastIndexOf

public int lastIndexOf(int ch, int fromIndex):

从指定的索引处开始进行反向搜索,

如果此字符串中有这样的字符,则返回指定字符在此字符串中最后一次出现处的索引

如果此字符串中没有这样的字符,则返回 -1

substring

public static String substring(Object self,int start,int end)

对指定内容进行分割,start为起始位置,end为终止位置

返回值为分割好的一段一段的内容。

lastIndexOf和subString综合应用

应用场景:

将传入的文本内容,按固定长度进行分割,其中完整的单词不能被截断

具体操作:

public void insertAritcleLineByLine(String text, int length) {
        List<TypArticleModel> listTyp = new ArrayList<>();
        //遍历整篇文章,按固定长度截取,同时不截断单词,设定截取位置从0开始
        for (int index = 0; index < text.length(); index++) {
            //设置起始位置
            int startIndex = index;
            //设置终止位置=起始位置+固定长度
            int endIndex = startIndex+length;
            if (endIndex>= text.length())
            {
                //文章总长<设定的固定截取长度,则直接将文章总长设定为截取位置
                index=text.length();
            }else
            {
                //终止位置的最后一个字符是空格
                int i=text.lastIndexOf(' ',endIndex);
                //如果最后一个字符不是空格,或着空格位置是起始位置,则设定当前位置为终止位置
                if(i<0 || i==startIndex){
                    index = endIndex;
                }else
                {
                    //如果满足最后一个字符是空格,则设置当前位置为i(即最后一个空格的位置)
                    index=i;
                }
            }
            //截取成子字符串
            String childText = substring(text, startIndex, index);
}

猜你喜欢

转载自blog.csdn.net/YaraRen/article/details/109209026