Java: How to split a string by a number of characters?

前端 未结 11 1479
夕颜
夕颜 2020-11-27 06:59

I tried to search online to solve this question but I didn\'t found anything.

I wrote the following abstract code to explain what I\'m asking:

String         


        
11条回答
  •  猫巷女王i
    2020-11-27 07:19

    My application uses text to speech! Here is my algorithm, to split by "dot" and conconate string if string length less then limit

    String[] text = sentence.split("\\.");
     ArrayList realText =  sentenceSplitterWithCount(text);
    

    Function sentenceSplitterWithCount: (I concanate string lf less than 100 chars lenght, It depends on you)

    private ArrayList sentenceSplitterWithCount(String[] splittedWithDot){
    
            ArrayList newArticleArray = new ArrayList<>();
            String item = "";
            for(String sentence : splittedWithDot){
    
                item += DataManager.setFirstCharCapitalize(sentence)+".";
    
                if(item.length() > 100){
                    newArticleArray.add(item);
                    item = "";
                }
    
            }
    
            for (String a : newArticleArray){
                Log.d("tts", a);
    
            }
    
            return newArticleArray;
        }
    

    function setFirstCharCapitalize just capitalize First letter: I think, you dont need it, anyway

       public static String setFirstCharCapitalize(String input) {
    
    
            if(input.length()>2) {
                String k = checkStringStartWithSpace(input);
                input = k.substring(0, 1).toUpperCase() + k.substring(1).toLowerCase();
            }
    
            return input;
        }
    

提交回复
热议问题