0

So I'm trying to write a method that will split strings that are longer than 160 by inserting the xml tag . I have tried to use and modify java's wordWrap method. But this seems to split sentences at fullstops or . I do not want this to happen because these strings have ID's in them that show as follows : FID.1262.

The mothod I currently have:

private String tests(String Message) {
    StringBuilder text = new StringBuilder(Message);
    int size = Message.length();
    int size1 = 160;
    while (!Message.substring(size1 - 1, size1).equals(" ")) {
        size1--;
        if (Message.substring(size1 - 1, size1).equals(" ")) {
            text.insert(size1, "<SPLIT>");
            text.replace(size1 - 1, size1, "");
            return "" + text;
        }
    }
    text.insert(size1, "<SPLIT>");
    text.replace(size1 - 1, size1, "");
    text.trimToSize();
    return "" + text;
}

The output: This is a test message that will be split when the while loop iterates backwards through the string. It will then place an xml tag with split in is in the lastspace before 160 characters.

The problem is this method will only split a string once no matter how long it is. What I need is for it to be able to split strings of n size at every 160 or less characters by the space.

if anyone can give me any pointers. This turned out to be much harder than it actually sounds...

DeanMWake
  • 893
  • 3
  • 19
  • 38

2 Answers2

1

What you need is java.text.BreakIterator

You will get the Word Iterator using

 BreakIterator#getWordInstance()

Here is a sample how to use it:

public static void main(String args[]) {
  if (args.length == 1) {
      String stringToExamine = args[0];
      //print each word in order
      BreakIterator boundary = BreakIterator.getWordInstance();
      boundary.setText(stringToExamine);
      int start = boundary.first();
      for (int end = boundary.next();
        end != BreakIterator.DONE;
        start = end, end = boundary.next()) {
        System.out.println(stringToExamine.substring(start,end));
      }
   }
}

above sample prints each word in the string. you can manipulate it as you want by adding the word lengths and if word lengths is greater than 160 don't add the next word instead add your

Hope this helps.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33
0

This might help you:

private int static LENGTH = 160;
public static List<String> splitByLength(String text) {
    List<String> ret = new ArrayList<String>((text.length()/ LENGTH + 1);
    for (int start = 0; start < text.length(); start += size) {
        ret.add("<SPLIT>" + text.substring(start, Math.min(text.length(), start + size)) + "<SPLIT>");
    }
    return ret;
}

(untested)

You can easly use that list to do what ever you want considering you have each entity is splitted. concatenate them

Reference: Split string to equal length substrings in Java

Community
  • 1
  • 1
Bogdan M.
  • 2,161
  • 6
  • 31
  • 53