Split a String to a String[] so that each element is maximum 100 characters and ends in a space

前端 未结 4 1029
囚心锁ツ
囚心锁ツ 2021-01-28 16:53

How do i do this? I tried something like this but I do not seem to be able to get any further.

public void speak(String text)
{
    String[] textArray = text.spl         


        
4条回答
  •  既然无缘
    2021-01-28 16:56

    For wrapping text, rather than focusing on the spaces, focus on the 100 character limit. For most text, spaces will occur far more often than once per 100 characters.

    public void speak(String text) {
        while(text.length() > 100) {
            int nextSpace = text.lastIndexOf(" ", 99);
            if (nextSpace == -1) { //no spaces for 100 characters
                System.out.println(text.substring(0, 100));//give as many characters as possible, then split anyway
                text = text.substring(100);
                continue;
            }
            System.out.println(text.substring(0, nextSpace));
            text = text.substring(nextSpace + 1);
        }
        System.out.println(text);
    }
    

提交回复
热议问题