【问题标题】:Wrap the string after a number of characters word-wise in Java在 Java 中逐字地在多个字符之后包装字符串
【发布时间】:2018-03-22 20:26:16
【问题描述】:

我有这个代码:

    String s = "A very long string containing " +
                   "many many words and characters. " +
                   "Newlines will be entered at spaces.";

    StringBuilder sb = new StringBuilder(s);

    int i = 0;
    while ((i = sb.indexOf(" ", i + 20)) != -1) {
        sb.replace(i, i + 1, "\n");
    }

    System.out.println(sb.toString());

代码的输出是:

A very long string containing
many many words and
characters. Newlines
will be entered at spaces.

上面的代码是在每 30 个字符的下一个空格之后包装字符串,但我需要在每 30 个字符的前一个空格之后包装字符串,就像第一行一样:

A very long string

第二行将是

containing many

请给出适当的解决方案。

【问题讨论】:

    标签: java


    【解决方案1】:
    【解决方案2】:

    使用lastIndexOf 代替indexOf,例如

    StringBuilder sb = new StringBuilder(s);
    
    int i = 0;
    while (i + 20 < sb.length() && (i = sb.lastIndexOf(" ", i + 20)) != -1) {
        sb.replace(i, i + 1, "\n");
    }
    
    System.out.println(sb.toString());
    

    这将产生以下输出:

    A very long string
    containing many
    many words and
    characters.
    Newlines will be
    entered at spaces.
    

    【讨论】:

    • 感谢您的回复。在此示例中,如果我提供字符串为“一个非常长的字符串 12222222222222222 包含许多单词和字符。将在空格处输入换行符。”那么输出不会在长字之后换行(“string122222222222222222222222222222”)并且在长字之前意外换行。
    • @Suvonkar:您可以查看WordUtils.wrap() 的来源并按照您喜欢的方式实现它。
    • 短小精悍,就像一个 C 程序员 :) sb.replace(i, i + 1, "\n"); -> sb.setCharAt( i, '\n' ); 是另一种选择
    【解决方案3】:

    您可以尝试以下方法:

    public static String wrapString(String s, String deliminator, int length) {
        String result = "";
        int lastdelimPos = 0;
        for (String token : s.split(" ", -1)) {
            if (result.length() - lastdelimPos + token.length() > length) {
                result = result + deliminator + token;
                lastdelimPos = result.length() + 1;
            }
            else {
                result += (result.isEmpty() ? "" : " ") + token;
            }
        }
        return result;
    }
    

    调用为 wrapString("asd xyz afz","\n",5)

    【讨论】:

      【解决方案4】:

      我知道这是一个老问题,但是 . . .根据我在这里找到的另一个答案,但不记得海报的名字。感谢他/她为我指明了正确的方向。

          public String truncate(final String content, final int lastIndex) {
              String result = "";
              String retResult = "";
              //Check for empty so we don't throw null pointer exception
              if (!TextUtils.isEmpty(content)) {
                  result = content.substring(0, lastIndex);
                  if (content.charAt(lastIndex) != ' ') {
                      //Try the split, but catch OutOfBounds in case string is an
                      //uninterrupted string with no spaces
                      try {
                          result = result.substring(0, result.lastIndexOf(" "));
                      } catch (StringIndexOutOfBoundsException e) {
                          //if no spaces, force a break
                          result = content.substring(0, lastIndex);
                      }
                      //See if we need to repeat the process again
                      if (content.length() - result.length() > lastIndex) {
                          retResult = truncate(content.substring(result.length(), content.length()), lastIndex);
                      } else {
                          return result.concat("\n").concat(content.substring(result.length(), content.length()));
                      }
                  }
                  //Return the result concatenating a newline character on the end
                  return result.concat("\n").concat(retResult);;
                  //May need to use this depending on your app
                  //return result.concat("\r\n").concat(retResult);;
              } else {
                  return content;
              }
          }
      

      【讨论】:

        【解决方案5】:
        public static void main(String args[]) {
        
                 String s1="This is my world. This has to be broken.";
                 StringBuffer buffer=new StringBuffer();
        
                 int length=s1.length();
                 int thrshld=5; //this valueis threshold , which you can use 
                 int a=length/thrshld;
        
                 if (a<=1) {
                     System.out.println(s1);
                 }else{
                    String split[]=s1.split(" ");
                    for (int j = 0; j < split.length; j++) {
                        buffer.append(split[j]+" "); 
        
                        if (buffer.length()>=thrshld) { 
        
                            int lastindex=buffer.lastIndexOf(" ");
        
                            if (lastindex<buffer.length()) { 
        
                                buffer.subSequence(lastindex, buffer.length()-1);
                                System.out.println(buffer.toString()); 
                                buffer=null;
                                buffer=new StringBuffer();
                            }
                        }
                    }
                 }
             }
        

        这可能是一种实现方式

        【讨论】:

          【解决方案6】:

          "\n" 进行自动换行。

          String s = "A very long string containing \n" +  
          "many many words and characters. \n" +
          "Newlines will be entered at spaces.";
          

          这会解决你的问题

          【讨论】:

          • 为什么我没有早点想到这个??
          猜你喜欢
          • 1970-01-01
          • 2013-01-18
          • 1970-01-01
          • 2015-06-19
          • 2012-03-06
          • 2016-01-09
          • 2012-08-02
          • 1970-01-01
          • 2019-03-12
          相关资源
          最近更新 更多