如何在一定长度后拆分字符串?但是应该在单词完成后进行分割 [英] How to split a string after a certain length? But it should be divided after word completion

查看:49
本文介绍了如何在一定长度后拆分字符串?但是应该在单词完成后进行分割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个字符串分成一定长度后的字符串列表.示例我想在第 50 个字符之后分割一个字符串,但如果第 50 个字符单词未完成,则应在单词完成后分割

I want to divide a string into a list of strings after a certain length. Example I want to divide a string after the 50th but if the 50th character word is not completed it should divide after word completion

List<String> remarksList = new ArrayList<>();
String remarks = "I want to split in to multiple strings after every" +
        " 50 charcters but if there any word not completed it should" +
        " be divded after word completion";
int length = remarks.length();
for (int i = 0; i < length; i += NoaConstant.ARRIVAL_FREE_TEXT_LENGTH) {
    remarksList.add(remarks.substring(i,
            Math.min(length, i + NoaConstant.ARRIVAL_FREE_TEXT_LENGTH)));
}

推荐答案

这是一种简单的方法.它假定一个空格分隔单词.它的工作原理如下:

Here is one simple way to do it. It presumes that a space separates words. It works as follows:

  • 找到从字符串的所需长度开始的第一个空格的索引.
  • 如果返回值为 -1(未找到空格),则使用字符串长度.
  • 获取从 0 到该索引的子字符串.
  • 如果这是字符串的结尾,则中断.
  • else 用字符串的其余部分替换起始文本,跳过刚刚找到的空格.
String remarks = "I want to split in to multiple strings after every 50 charcters but if there any word not completed it should be divded after word completion";

int length = 50;
List<String> remarksList = new ArrayList<>();
for(;;) {
       int end = remarks.indexOf(" ", length);
       end = end >= 0 ? end : remarks.length();
       String substr = remarks.substring(0,end);
       remarksList.add(substr);
       if (end >= remarks.length()) {
           break;
       }
       remarks = remarks.substring(end+1);
}

remarksList.forEach(System.out::println);

印刷品

I want to split in to multiple strings after every
50 charcters but if there any word not completed it
should be divded after word completion

这篇关于如何在一定长度后拆分字符串?但是应该在单词完成后进行分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆