2017-10-16 88 views
1

我想用我的最大允许字符的最后空间来分割字符串:分裂与最大字符的最后一个空格的字符串

后市展望:

字符串名称=“约翰·大卫·库塔马克·亨利Anthoney山姆“;

最大允许的字符:

因此,它应该是返回:

John David Guetta MarkHenry 
Anthoney Sam 

实际结果:

John David Guetta MarkHenry An 
thoney Sam 

代码:

public static List<String> splitByLength(String str, int n) { 
    List<String> returnList = new ArrayList<>(); 
    StringBuilder sb = new StringBuilder(); 

    for (int i = 0; i < str.length(); i++) { 
     if (i > 0 && (i % n == 0)) { 
      returnList.add(sb.toString()); 
      sb = new StringBuilder(); 
     } 

     sb.append(str.charAt(i)); 
    } 
    if (StringUtils.isNoneBlank(sb.toString())) { 
     returnList.add(sb.toString()); 
    } 
    return returnList; 
} 

回答

1

你可以使用接受最多30个字符正则表达式:

String name = "John David Guetta MarkHenry Anthoney Sam"; 
Pattern p = Pattern.compile(".{1,30}(\\s+|$)"); 
Matcher m = p.matcher(name); 
while(m.find()) { 
    System.out.println(m.group().trim()); 
} 

注意(\\s|$)打破无论是在空间或一旦达到初始字符串的结尾。

+0

我希望我可以upvote 1000次..感谢节省我的时间... –

1

我困难和麻烦的使用正则表达式它总能找到,所以这里是我会用

private static void splitByLength(String str, int n) { 
    String newStr = ""; 
    int splitIndex = 0; 
    for (int i = 0; i < str.length(); i++) { 
     if (str.charAt(i) != ' ') {  
      newStr = newStr + str.charAt(i); //Keep adding chars until you find a space 
      if (newStr.length() > n) { //If newStr's length exceeds 'n', break the loop 
       break; 
      } 
     } else { 
      splitIndex = i; //Store the last space index 
      newStr = newStr + ' '; 
     } 
    } 
    System.out.println(str.substring(0, splitIndex).trim()); //Use the splitIndex to print a substring 
    System.out.println(str.substring(splitIndex, str.length()).trim()); 
} 
-1

也许有趣

String name = "John David Guetta MarkHenry Anthoney Sam"; 
    StringBuilder myName = new StringBuilder(name); 
    if(name.length() > 30) { 
     myName.setCharAt(27, '\n'); 
    } 
    System.out.println(myName); 

输出的解决方案:

约翰·大卫·库塔马克·亨利

Anthoney Sam

相关问题