Tuesday, 29 March 2016

Split Text After Space for specified number of characters


/**
  * Break the text for specified no of characters after sapce
  * @param text , Which we have to break
  * @param noOfCharacters No of char on which we have to break the message
  * @param splitChar On which char we have to split the string eg. '\n'
  * @param splited text
  */
  public static String splitTextAfterSpace(String text, int noOfChar, char splitChar){
        if(text != null) {
            StringBuffer stBuffer = new StringBuffer(1024);
            int length = text.length();
            int startIndex = 0;
            int endIndex = startIndex + noOfChar;
            while(true) {    
              // iterate till number of tokens of string
              // [assume: remaining part is left after loop]
              String token = text.substring(startIndex, endIndex);
 
              // if broken string doesn't end with space char
              if(SPACE_CHAR != token.charAt(token.length()-1)) {
              
               // search for space after the word
               int spaceIdx = text.indexOf(SPACE_CHAR, endIndex-1);   
              
               // if space found, after the word
               if(spaceIdx != -1) { 
                   // assign new end index for breaking the word
                   endIndex = spaceIdx + 1;  
               } else {
                   // pick token till end of text
                   endIndex = length - 1;  
                   break;
               }
               token = text.substring(startIndex, endIndex);
              }

              stBuffer.append(token);   // add token
              stBuffer.append(splitChar);  // add split char
              
              // increase the start and end index
              startIndex = endIndex;
              endIndex = startIndex + noOfChar;
              if(endIndex >= length-1) {
                    // pick token till end of text
                    endIndex = length-1;   
                    break;
              }
            }

            // add the remaining part of text
            stBuffer.append(text.substring(startIndex));  
            return stBuffer.toString();      
        } else {
            return EMPTY_STRING;
        }   
    }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.