Split string into multiple strings if too long

Discussion in 'Plugin Development' started by r3Fuze, Jan 25, 2012.

Thread Status:
Not open for further replies.
  1. Heres what I'm trying to do:
    String myString = "This is my string that is too long!";
    Lets say I only have room for 10 letters per line. I would need to split myString into 4 lines without splitting the words in half.

    What the output should look like:
    "This is my"
    "string"
    "that is too"
    "long!"

    This is what I tried doing, it cuts words in half and misses the last part of the string:
    Code:java
    1.  
    2. String[] txt = myString.trim().split(" ");
    3. int max = 10;
    4. List<String> lines = new ArrayList<String>();
    5. String s1 = "";
    6. if (!(myString.length() > max)) {
    7. lines.add(myString);
    8. } else {
    9. for (int i = 0; i < txt.length; i++) {
    10. if (!((s1 + txt + " ").length() <= max)) {
    11. lines.add(s1 + txt);
    12. s1 = "";
    13. }
    14. s1 += txt + " ";
    15. }
    16. }
    17. int yo = 0;
    18. for (String s : lines) {
    19. //draw(s, x, yo)
    20. yo += 10;
    21. }
     
  2. Offline

    RROD

    Code:Java
    1. String msg = "this,is,a,message,that,can,be,split,into,an,array";
    2. String[] splitMsg = msg.split(",");
    3.  
    4. // To test.
    5. for (i=0;i<splitMsg.length();i++) {
    6. log.info(splitMsg);
    7. }


    See if you can make something out of this.
     
  3. Offline

    hatstand

    r3Fuze You could find the last index of a space before 10 characters using lastIndexOf(" ", 10) if I recall correctly. You could them grab the substring between the start and that index (To get the line), grab the string between that index and the end, and repeat the process on the remainder until lastIndexOf returns -1.

    RROD Try reading the OP next time.
     
  4. Offline

    RROD

    Yeah, I realised after posting.
     
  5. Offline

    Technius

    Code:java
    1.  
    2. String[] tokens = myString.trime().split(" ");
    3. List<String> lines = new ArrayList<String>();
    4. String temp = "";
    5. for(String s: lines)
    6. {
    7. if(s.length() + temp.length() > 10)
    8. {
    9. lines.add(temp);
    10. temp = "";
    11. }
    12. temp = temp + s;
    13. }
    14.  


    The problem is that a word that is longer than 10 will make an infinite loop, so you could do this:
    Code:java
    1.  
    2. for(String s: lines)
    3. {
    4. if(s.length() > 10)throw new IllegalArgumentException("This string is too long!");
    5. if(s.length() + temp.length() > 10)
    6. {
    7. lines.add(temp);
    8. temp = "";
    9. }
    10. temp = temp + s;
    11. }
    12.  
     
Thread Status:
Not open for further replies.

Share This Page