为了账号安全,请及时绑定邮箱和手机立即绑定

如何每n个字符剪切一个字符串?但只有在有空格时才会削减

如何每n个字符剪切一个字符串?但只有在有空格时才会削减

宝慕林4294392 2022-06-04 09:35:31
我试图将一个长字符串切割成该字符串的行,行的长度由函数决定。该功能不会剪切中间的单词。我尝试了很多方法来使用子字符串等,但我不擅长字符串操作。我在网上发现了一个类似的问题,但它是在 JavaScript 中,并且一些我无法完全翻译成 Java 的代码(可能是因为我对它没有经验......)public static List<String> descriptionFormatter(String string, int amt){    String[] splitted = string.split(" ");    String part = "";    List<String> finalDesc = new ArrayList<String>();    for(int i = 0 ; i < splitted.length; i++)    {        part = part + " " + splitted[i];        if(part.length() >= amt)        {            finalDesc.add(part);            part = "";        }    }    return finalDesc;}例如,我有一个字符串“你好世界苹果橙葡萄汁意大利面酱牛奶”,我想每 34 个字符切割一次(考虑到上述所有要求)所以我打电话descriptionFormatter(string, 34);想要的结果是一个字符串数组/列表:你好世界苹果橙葡萄汁意大利面酱牛奶实际结果:你好世界苹果橙葡萄汁我已经几乎让它工作了,但有时它会在最后跳过剩余的单词并在第一个单词之前放置空格。我如何使它按我的意图运行?
查看完整描述

3 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

您可以尝试string使用两个索引遍历输入beginIndex,endIndex并在执行过程substrings中从输入string中获取:


public static List<String> descriptionFormatter(String str, int amt) {

    List<String> result = new ArrayList<>();


    // trim the input string to avoid empty strings at the end

    str = str.trim();


    int beginIndex = 0;  

    int endIndex = amt; 


    final int length = str.length();

    while(endIndex < length) {

        // if we landed on something other than space

        // increase the end index for the substring

        // until we hit a space

        while(endIndex < length && str.charAt(endIndex) != ' ') {

            ++endIndex;

        }

        result.add(str.substring(beginIndex, endIndex).trim());


        beginIndex = endIndex;

        endIndex += amt;

    }

    // Add the last string if any left

    if(beginIndex < length) {

        result.add(str.substring(beginIndex).trim());

    }

    return result;

}


public static void main(String[] args) {

    String str = "hello world apple orange grapes juice spagehtti sauce milk";

    descriptionFormatter(str, 34).forEach(System.out::println);

}

输出:


hello world apple orange grapes juice

spagehtti sauce milk


查看完整回答
反对 回复 2022-06-04
?
慕哥9229398

TA贡献1877条经验 获得超6个赞

    public static List<String> descriptionFormatter(String string, int amt) {

        List<String> stringPieces = new ArrayList<>();

        StringBuilder strOfMaxLen = new StringBuilder();

        StringBuilder strExceedsMaxLen = new StringBuilder();

        String[] splitted = string.split(" ");


        for (int i = 0 ; i < splitted.length; i++) {


            String piece = splitted[i];

            int pieceLen = piece.length();


            if (strOfMaxLen.length()+pieceLen < amt) {

                if (strOfMaxLen.length() != 0) {

                    strOfMaxLen.append(" ");

                }

                strOfMaxLen.append(piece);

            } else {

                if (strExceedsMaxLen.length() != 0) {

                    strExceedsMaxLen.append(" ");

                }

                strExceedsMaxLen.append(piece);

            }

        }

        stringPieces.add(strOfMaxLen.toString());

        stringPieces.add(strExceedsMaxLen.toString());


        return stringPieces;

    }


查看完整回答
反对 回复 2022-06-04
?
不负相思意

TA贡献1777条经验 获得超10个赞

尝试这样做



static List<String> split(String s, int size) { 

  return split(s.toCharArray(), size);

}


static List<String> split(char[] s, int size) {

  List<String> strs = new ArrayList<>();

  StringBuilder sb = new StringBuilder();


  for (int i = 0; i < s.length; ++i) {

    if (i % size == 0) {

      if(s[i] == ' ') {

        strs.add(sb.toString());

        sb = new StringBuilder();

      }else {

        StringBuilder newStringBuilder = new StringBuilder();

        int length = sb.length();

        while (length > 0 && sb.charAt(length - 1) != ' ') {

          newStringBuilder.insert(0, sb.charAt(length -  1));

          sb.deleteCharAt(length - 1);

          --length;

        }

        if(sb.length() > 0) strs.add(sb.toString());

        sb = newStringBuilder;

      }

    }

    sb.append(s[i]);

  }

  if (sb.length() > 0) {

    strs.add(sb.toString());

  }

  return strs;

}


查看完整回答
反对 回复 2022-06-04
  • 3 回答
  • 0 关注
  • 120 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号